JDBC Lecture12
JDBC Lecture12
Database
JAVA Applet/ JDBC Call Command
Application JDBC Driver Database
Overview (2/2)
Reason for JDBC
Database vendors (Microsoft Access, Oracle etc.) provide
proprietary (non standard) API for sending SQL to the server
and receiving results from it
Languages such as C/C++ can make use of these proprietary
APIs directly
High performance
Database
JDBC Programming Steps
1) Create a statement
Query 2) Query the database
While(rs.next())
{
Executing SQL
Int x = rs.getInt(“a”);
String s = rs.getString(“b”);
Float f = rs.getFloat(“c”); Processing the result set
}
rs.close();
stmt.close();
con.close(); Closing the connections
Step 1 : Loading a JDBC Driver
A JDBC driver is needed to connect to a database
Loading a driver requires the class name of the driver.
Ex) JDBC-ODBC: sun.jdbc.odbc.JdbcOdbcDriver
Oracle driver: oracle.jdbc.driver.OracleDriver
MySQL: com.mysql.jdbc.Driver
Class.forName("com.mysql.jdbc.Driver");
Protocol:
Protocol: JDBC
JDBC isis Sub-protocol:
Sub-protocol: Subname:
Subname: indicates
indicates the
the location
location and
and
the
the only
only protocol
protocol inin identifies
identifies aa name
name of
of the
the database
database toto be
be
JDBC
JDBC database
database accessed.
accessed. Syntax
Syntax is
is driver
driver specific
specific
driver
driver
Ex) jdbc:mysql://oopsla.snu.ac.kr/mydb
Step 2 : Connecting to a Database (2/2)
Connection connection =
DriverManager.getConnection("jdbc:mysql://oopsla.snu.ac.kr/mydb",“useri
d",“password");
JDBC
JDBC URL URL
Vendor
Vendorofofdatabase,
database,Location
Locationofof Username
Username Password
Password
database
databaseserver
serverand
andname
nameofof
database
database
Step 3 : Executing SQL (1/2)
Statement object
Can be obtained from a Connection object
Example
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(“SELECT ID, name, score FROM table1”);
NOTE
While (rs.next()){ You must step the cursor to the first record before read the results
int id = rs.getInt(“ID”); This code will not skip the first record
String name = rs.getString(“name”);
float score = rs.getFloat(“score”);
System.out.println(“ID=” + id + “ ” + name + “ ” + score);}