Presentation is loading. Please wait.

Presentation is loading. Please wait.

Jaeki Song JAVA Lecture 11 Java Database Connectivity.

Similar presentations


Presentation on theme: "Jaeki Song JAVA Lecture 11 Java Database Connectivity."— Presentation transcript:

1 Jaeki Song JAVA Lecture 11 Java Database Connectivity

2 Jaeki Song JAVA Outline Introduction Java Database Connectivity

3 Jaeki Song JAVA Introduction File processing –Random access or sequential –Only allow access to data Cannot query Database systems –Mechanisms to organize and store data –Allow sophisticated queries –Relational database - most popular style Microsoft Access, Sybase, Oracle Structured Query Language (SQL, "sequel") –Queries relational databases –Can write Java programs to use SQL queries

4 Jaeki Song JAVA Database Language Database language –Used to access database –Can use high-level languages Java, C, C++, Visual Basic, COBOL, PL/I, Pascal Make requests using a specially designed query language Host language

5 Jaeki Song JAVA Relational Database Model Database models –Hierarchal, network, relational (most popular) –Focus on relational Relational Database Model –Composed of tables Rows called records Columns are fields (attributes) –First field usually primary key Unique for each record Primary key can be more than one field (column) Primary key not required

6 Jaeki Song JAVA Relational Database Structure NumberNameDepartmentSalaryLocation 23603 24568 35761 34589 47132 78321 JONES, A. KERWIN, R. LARSON, P. MYERS, B. NEUMANN, C. STEPHENS, T. 413 642 611 413 611 1100 2000 1800 1400 9000 8000 NEW JERSEY LOS ANGELES ORLANDO NEW JERSEY ORLANDO Table: Employee A record A columnPrimary Key

7 Jaeki Song JAVA Advantages Tables easy to use, understand, and implement Easy to convert other database structures into relational scheme –Universal Projection and join operations easy to implement Searches faster than schemes with pointers Easy to modify - very flexible Greater clarity and visibility than other models

8 Jaeki Song JAVA Java Database Connectivity You can access data files in Java using JDBC –JDBC classes handle communication between your Java program and a database driver –Java uses JDBC-ODBC Bridge

9 Jaeki Song JAVA Data Source Name (DSN) Before using JDBC in a Window environment, you need to create a DSN –DSN registers your database files on the computer Setting up a DSN –Step1: From the start menu, select control panel –Step2: select ODBC Data source –Step3: On the User DSN tab, click on the Add button

10 Jaeki Song JAVA Data Source Name (DSN)

11 Jaeki Song JAVA Data Source Name (DSN) –Step4: Select the database type (Microsoft Access database), and click Finish

12 Jaeki Song JAVA Data Source Name (DSN) –Step5: Type in the Data Source Name

13 Jaeki Song JAVA Data Source Name (DSN) –Step6: Use the Select (or Browse) button to locate the file, then close the dialog boxes

14 Jaeki Song JAVA JDBC-ODBC Bridge Driver In Java code, you must connect to the driver using the Class.forName method –Connect to Microsoft’s driver Class.forName(“com.ms.jdbc.odbc.JdbcOdbcDriver” ); –Connect to Sun’s driver Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

15 Jaeki Song JAVA JDBC-ODBC Bridge Driver If you need to be able to load either driver, you can use try/catch block try { Class.forName(“com.ms.jdbc.odbc.JdbcOdbcDriver”); } catch {try {Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);} catch(ClassNotFoundException err) { System.err.println(“Driver did not load properly”);} }

16 Jaeki Song JAVA Connecting to the Database Next step is to connect to the database using the name that your registered as a DSN “jdbc:odbc:EX1” Use DriverManager.getConnection method and assign it to a Connection object conEmployees = DriverManager.getConnection(“jdbc:odbc:EX1” );

17 Jaeki Song JAVA Connecting to the Database //Declare a Connection object Connection conEmployees; //Connect to the database try { conEmployees = DriverManager.getConnection (“jdbc:odbc:EX1”); } catch(SQLException err) { statement // “No connection to database” }

18 Jaeki Song JAVA Creating a ResultSet A ResultSet object contains a collection of records from the database –To create ResultSet, you must declare a Statement object and call the Connection objects’ createStatement method Statement cmdEmployees; ResultSet rsEmployees; –You create a ResultSet with an SQL query with executeQuery method Select * from Employees cmdEmployees.executeQuery(“Select * from Employees”);

19 Jaeki Song JAVA Example try { Connection conEmployees; conEmployees = DriverManager.getConnection (“jdbc:odbc:EX1”); //create a ResultSet Statement cmdEmployees = conEmployees.createStatement(); ResultSet rsEmployees = cmdEmployees.executeQuery (“Select * from Employees”); } catch(SQLException err) { statement // “No connection to database” }

20 Jaeki Song JAVA Example You can create an SQL statement to create a ResultSet that matches a given condition ResultSet rsEmployees = cmdEmployees.executeQuery ( “Select * from Employees Where [Last Name] = ‘Song’ ; ”); ResultSet rsEmployees = cmdEmployees.executeQuery ( “Select * from Employees Where [Last Name] = ‘ “ + strLastName + ” ’ ; ”);

21 Jaeki Song JAVA Retrieving a Record Looping through a ResultSet Displaying the fields from a record

22 Jaeki Song JAVA Retrieving a Record When you first open a ResutSet, the current-record is located just prior to the first record You call the ResultSet’s next method –The next method moves the current-record pointer to the first record and returns boolean value true: the next record exists false: no more records exists

23 Jaeki Song JAVA Example try { rsEmployees.next( ); lstNames.add(rsEmployees.getString (“Last Name”)); } catch (SQLException err) { System.err.println(“Error : “ + err.toString()); } The getString method retrieves the data for the specified string field

24 Jaeki Song JAVA Looping through a ResultSet You can step through all records in a ResultSet using a loop –while (rsResultSet.next( )) to control the loop –The boolean condition tests true as long as records remain in the ResultSet while(rsEmployees.next( )) lstNames.add(rsEmployees.getString(“Last Name”));

25 Jaeki Song JAVA Displaying the Fields try { //display information if (rsEmployees.next( )) { lblFirstName.setText(rsEmployees.getString(“ First Name”); lblSSN.setText(rsEmployees.getString(“SSN”)); lblSSN.setText(rsEmployees.getString(“Phone Number”)); } else //Statement } catch (SQLException err) { System.err.println(“Error : “ + err.toString()); }

26 Jaeki Song JAVA Accessing the Data Fields Access the data in database fields by using the appropriate method for the data type –getString for string field –getFloat or getInt for float or int fields Convert the value to a string format to display the value in a label or text field

27 Jaeki Song JAVA Closing the Connection Make sure that the database connection is closed at the termination of the program –Place the statement in the stop method –Place the code in your exit routine public void stop( ) { if (conEmployees != null) conEmployees.close( ); }

28 Jaeki Song JAVA SQL Java’s JDBC uses Structured Query Language (SQL) to create a ResultSet ResultSet rsEmployees = cmdEmployees.executeQuery(“Select * from Employees”); ResultSet rsEmployees = cmdEmployees.executeQuery(“Select * from Employees where [Last Name] = ‘ “ + strLastName + ” ’; ”);

29 Jaeki Song JAVA Types of SQL Statement For the field(s), you can list the field names or use an asterisk to indicate all fields from the named table. –Multiple-world field names must be enclosed in square brackets or accent grave marks (‘) –The closing semicolon(;) is specified in the SQL standards

30 Jaeki Song JAVA SQL Examples SELECT “Select * from Employees;” Where “Select * from Employees where [Last Name] = ‘ ABC’ ”; “Select * from Employees where [Last Name] = ‘ “ + strLastName + ”’; ”

31 Jaeki Song JAVA Adding a Record SQL insert statement-General format Insert Into TableName (FieldList) Values (ListOfValue) Use the statement object’s executeUpdate method to excute the SQL Insert Into statement

32 Jaeki Song JAVA Example cmdEmplyees.executeUpdate (“ Insert Into Employees” + “( [Last Name], [First Name], SSN, [Phone Number]) ” + “Values( ‘ “ + txtLastName.getText() + ” ’, ‘ “ + txtFirstName.getText( ) + ” ’)”);

33 Jaeki Song JAVA Finding a Record SQL Statement strLastName = txtLastName.getText(); String query = “Select *from Employees where [Last Name] = ‘ “ + strLastName + ’ ” ”; rsEmployees = statement.executeQuery(query);


Download ppt "Jaeki Song JAVA Lecture 11 Java Database Connectivity."

Similar presentations


Ads by Google