Professional Documents
Culture Documents
Java II Lecture 4.pps
Java II Lecture 4.pps
Chapter 18
JDBC
* Toy Database
Java II--Copyright © 2001-2004 Tom Hunter
Background: databases
• Types of databases
IDID LastName
LastName FirstName
FirstName Age
Age Code
1 1 Jones
Jones Sam
Sam 32
32 A
2 2 Jones
Jones Angela
Angela 27
27 B
33 Smith
Smith Ann
Ann 22
22 A
44 Doe
Doe Jack
Jack 44
44
SELECT columns
FROM table
WHERE expression
Example:
UPDATE table
SET LastName = ‘Jones’
WHERE ID = 2;
Example:
Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver” );
• The above statement will merely ensure that the Java class
containing the driver is available to our program.
username
password
url
url = jdbc:oracle:thin:@myhostname:1521:OurDB
myhostname —This is the name of the host where the database is located.
1521 —This is the port on the host where the database is listening.
import java.sql.Connection;
…
Connection con = DriverManager.getConnection( url, user, pass );
ResultSet rs = pstmt.executeQuery();
ResultSet rs = cstmt.executeQuery();
These correspond to
columns in the original
query.
Java II--Copyright © 2001-2004 Tom Hunter
JDBC Basics: ResultSet
• No matter which kind of statement you choose, the
ResultSet object is used the same way.
• As with the Connection object, you must close your
ResultSet!
while( rs.next() )
{
output = rs.getString( “username” );
}
rs.close();
stmt.close(); You must close these
con.close();
} three items, in the reverse
catch( SQLException sql ) order that you opened
{
System.out.println( “Uh oh…” ); them!
}