JAVA Jaeki Song Lecture 11 Java Database Connectivity
JAVA
Jaeki Song
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
JAVA
Jaeki Song
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
JAVA
Jaeki Song
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
JAVA
Jaeki Song
Relational Database Structure
Number Name DepartmentSalary Location
2360324568
35761
34589
47132
78321
JONES, A.
KERWIN, R.
LARSON, P.
MYERS, B.
NEUMANN, C.
STEPHENS, T.
413
413
642
611
413
611
1100
2000
1800
1400
9000
8000
NEW JERSEY
NEW JERSEY
LOS ANGELES
ORLANDO
NEW JERSEY
ORLANDO
Table: Employee
A record
A columnPrimary Key
JAVA
Jaeki Song
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
JAVA
Jaeki Song
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
JAVA
Jaeki Song
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
JAVA
Jaeki Song
Data Source Name (DSN)
– Step4: Select the database type (Microsoft Access database), and click Finish
JAVA
Jaeki Song
Data Source Name (DSN)
– Step6: Use the Select (or Browse) button to locate the file, then close the dialog boxes
JAVA
Jaeki Song
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 driverClass.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
JAVA
Jaeki Song
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”);}
}
JAVA
Jaeki Song
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 objectconEmployees =
DriverManager.getConnection(“jdbc:odbc:EX1”);
JAVA
Jaeki Song
Connecting to the Database
//Declare a Connection objectConnection conEmployees;
//Connect to the databasetry{conEmployees = DriverManager.getConnection (“jdbc:odbc:EX1”);}catch(SQLException err){ statement // “No connection to database”}
JAVA
Jaeki Song
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”);
JAVA
Jaeki Song
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”}
JAVA
Jaeki Song
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 + ” ’ ; ”);
JAVA
Jaeki Song
Retrieving a Record
• Looping through a ResultSet
• Displaying the fields from a record
JAVA
Jaeki Song
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
JAVA
Jaeki Song
Example
try{ rsEmployees.next( ); lstNames.add(rsEmployees.getString (“Last Name”));}catch (SQLException err){ System.err.println(“Error : “ + err.toString());}
The getString method retrieves the datafor the specified string field
JAVA
Jaeki Song
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”));
JAVA
Jaeki Song
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());}
JAVA
Jaeki Song
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
JAVA
Jaeki Song
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( );
}
JAVA
Jaeki Song
SQL
• Java’s JDBC uses Structured Query Language (SQL) to create a ResultSetResultSet rsEmployees =
cmdEmployees.executeQuery(“Select * from Employees”);
ResultSet rsEmployees = cmdEmployees.executeQuery(“Select * from Employees where [Last Name] = ‘ “ + strLastName + ” ’; ”);
JAVA
Jaeki Song
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
JAVA
Jaeki Song
SQL Examples
• SELECT“Select * from Employees;”
• Where“Select * from Employees where [Last Name] = ‘
ABC’ ”;
“Select * from Employees where [Last Name] = ‘ “ + strLastName + ”’; ”
JAVA
Jaeki Song
Adding a Record
• SQL insert statement-General formatInsert Into TableName (FieldList) Values
(ListOfValue)
• Use the statement object’s executeUpdate method to excute the SQL Insert Into statement
JAVA
Jaeki Song
Example
cmdEmplyees.executeUpdate (“ Insert Into Employees” + “( [Last Name] , [First Name], SSN, [Phone Number]) ”
+ “Values( ‘ “
+ txtLastName.getText() + ” ’, ‘ “
+ txtFirstName.getText( ) + ” ’)”);