Download presentation
Presentation is loading. Please wait.
1
Lecture 11 Database Connection
Jaeki Song
2
Outline Introduction Java Database Connectivity
3
Introduction File processing Database systems
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
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
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
Relational Database Structure
Table: Employee Number Name Department Salary Location 23603 JONES, A. 413 1100 NEW JERSEY 24568 KERWIN, R. 413 2000 NEW JERSEY A record 34589 LARSON, P. 642 1800 LOS ANGELES 35761 MYERS, B. 611 1400 ORLANDO 47132 NEUMANN, C. 413 9000 NEW JERSEY 78321 STEPHENS, T. 611 8000 ORLANDO Primary Key A column
7
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
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
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
Data Source Name (DSN)
11
Data Source Name (DSN) Step4: Select the database type (Microsoft Access database), and click Finish
12
Data Source Name (DSN) Step5: Type in the Data Source Name
13
Data Source Name (DSN) Step6: Use the Select (or Browse) button to locate the file, then close the dialog boxes
14
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
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
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
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
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
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
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
Retrieving a Record Looping through a ResultSet
Displaying the fields from a record
22
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
Example try { rsEmployees.next( );
The getString method retrieves the data for the specified string field try { rsEmployees.next( ); lstNames.add(rsEmployees.getString (“Last Name”)); } catch (SQLException err) System.err.println(“Error : “ + err.toString());
24
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
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
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
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
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
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
SQL Examples SELECT Where “Select * from Employees;”
“Select * from Employees where [Last Name] = ‘ ABC’ ”; “Select * from Employees where [Last Name] = ‘ “ + strLastName + ”’; ”
31
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
Example cmdEmplyees.executeUpdate (“ Insert Into Employees” + “( [Last Name] , [First Name], SSN, [Phone Number]) ” + “Values( ‘ “ + txtLastName.getText() + ” ’, ‘ “ + txtFirstName.getText( ) + ” ’)”);
33
Finding a Record SQL Statement strLastName = txtLastName.getText();
String query = “Select *from Employees where [Last Name] = ‘ “ + strLastName + ’ ” ”; rsEmployees = statement.executeQuery(query);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.