jdbc tutorial - courses.cs.tau.ac.il
TRANSCRIPT
![Page 1: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/1.jpg)
JDBC TutorialMIE456 -
Information Systems Infrastructure II
Vinod MuthusamyNovember 4, 2004
![Page 2: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/2.jpg)
DatabaseDatabaseJDBCdriver
Java Database Connectivity (JDBC)
An interface to communicate with a relational database
Allows database agnostic Java codeTreat database tables/rows/columns as Java objects
JDBC driverAn implementation of the JDBC interfaceCommunicates with a particular database
Java app DatabaseJDBC calls
Database commandsJDBC
driverJDBCdriver
![Page 3: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/3.jpg)
JDBC Driver TypesType 1: JDBC-ODBC Bridge
JDBC-ODBC
Bridge
DB
Java
Application
ODBC
Note: in following illustrations, DB may be on either a local or remote machine
![Page 4: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/4.jpg)
JDBC Driver TypesType 2: Native API / Partially Java
Java
Application
Native
Client
JDBC
Driver
DB
![Page 5: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/5.jpg)
JDBC Driver Types
Type 3: Pure Java / Net Protocol.
Java
Application
JDBC
Driver (Java)Server DB
Net Protocol
![Page 6: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/6.jpg)
JDBC Driver Types
Type 4: Pure Java / Native Protocol.
Java
Application
JDBC
Driver (Java) DBNative Protocol
![Page 7: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/7.jpg)
Eclipse JDBC setup
Install driverDownload MySQL JDBC driver from the Web
http://dev.mysql.com/downloads/connector/j/5.0.htmlUnzip mysql-connector-xxx.jarAdd mysql-connector-xxx.jar to Eclipse project
Project Properties Java Build Path Libraries Add External JARs
![Page 8: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/8.jpg)
JDBC steps
1. Connect to database2. Query database (or insert/update/delete)3. Process results4. Close connection to database
![Page 9: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/9.jpg)
1. Connect to database
Load JDBC driverClass.forName("com.mysql.jdbc.Driver").newInstance();
Make connectionConnection conn = DriverManager.getConnection(url);
URLFormat: “jdbc:<subprotocol>:<subname>”jdbc:mysql://localhost/systemsDB
![Page 10: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/10.jpg)
2. Query databasea. Create statement
Statement stmt = conn.createStatement();
stmt object sends SQL commands to databaseMethods
executeQuery() for SELECT statementsexecuteUpdate() for INSERT, UPDATE, DELETE, statements
b. Send SQL statementsstmt.executeQuery(“SELECT …”);stmt.executeUpdate(“INSERT …”);
![Page 11: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/11.jpg)
3. Process resultsResult of a SELECT statement (rows/columns) returned as a ResultSet object
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
Step through each row in the resultrs.next()
Get column values in a rowString userid = rs.getString(“userid”);int type = rs.getInt(“type”);
users tableuserid firstname lastname password typeBob Bob King cat 0John John Smith pass 1
![Page 12: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/12.jpg)
Queries
Result Set Cursor:
15000Miri
15000Yossi
SALARYNAME
EMPLOYEE
Cursor after first call to rs.next()
Initial Cursor position
![Page 13: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/13.jpg)
Print the users tableResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {String userid = rs.getString(1);String firstname = rs.getString(“firstname”);String lastname = rs.getString(“lastname”);String password = rs.getString(4);int type = rs.getInt(“type”);System.out.println(userid + ” ” + firstname + ” ” +
lastname + ” ” + password + ” ” + type);}
users tableuserid firstname lastname password typeBob Bob King cat 0John John Smith pass 1
![Page 14: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/14.jpg)
Add a row to the users tableString str =
"INSERT INTO users VALUES('Bob', 'Bob', 'King',
'cat', 0)”;
// Returns number of rows in tableint rows = stmt.executeUpdate(str);
users tableuserid firstname lastname password typeBob Bob King cat 0
![Page 15: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/15.jpg)
4. Close connection to database
Close the ResultSet objectrs.close();
Close the Statement objectstmt.close();
Close the connectionconn.close();
![Page 16: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/16.jpg)
import java.sql.*;
public class Tester {public static void main(String[] args) {
try {// Load JDBC driverClass.forName("com.mysql.jdbc.Driver").newInstance();
// Make connectionString url =
“jdbc:mysql://128.100.53.33/GRP?user=USER&password=PASS”Connection conn = DriverManager.getConnection(url);
// Create statementStatement stmt = conn.createStatement();
// Print the users tableResultSet rs = stmt.executeQuery("SELECT * FROM users");while (rs.next()) {
...}
// Cleanuprs.close(); stmt.close(); conn.close();
} catch (Exception e) {System.out.println("exception " + e);
}}
![Page 17: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/17.jpg)
Queries: Joins
Joining tables with similar column names:You may need to read columns by index.
ResultSet rs = stmt.executeQuery(
“select p.NAME,s.NAME from PRODUCT p, SUPPLIER s where s.PROD_ID=p.ID “);
while(rs.next())
System.out.println( rs.getString(1) + “ “ + rs.getString(2));
ResultSet rs = stmt.executeQuery(
“select p.NAME,s.NAME from PRODUCT p, SUPPLIER s where s.PROD_ID=p.ID “);
while(rs.next())
System.out.println( rs.getString(1) + “ “ + rs.getString(2));
2Shampoo
1Tomatoes
IDNAME
product
2Hawaii
1Farmer1
PROD_IDNAME
supplier
HawaiiShampoo
Farmer1Tomatoes
supplier.NAMEproduct.NAME
JOIN
![Page 18: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/18.jpg)
TransactionsCurrently every executeUpdate() is “finalized” right away
Sometimes want to a set of updates to all fail or all succeed
E.g. add to Appointments and Bookings tablesTreat both inserts as one transaction
TransactionUsed to group several SQL statements togetherEither all succeed or all fail
![Page 19: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/19.jpg)
Transactions
CommitExecute all statements as one unit“Finalize” updates
RollbackAbort transactionAll uncommited statements are discardedRevert database to original state
![Page 20: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/20.jpg)
Transactions in JDBC
Disable auto-commit for the connectionconn.setAutoCommit(false);
Call necessary executeUpdate() statements
Commit or rollbackconn.commit();conn.rollback();
![Page 21: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/21.jpg)
Prepared Statements
A prepared statement is pre-compiled only once.Allows arguments to be filled in.Useful for:
Efficiency.Convenience.Handling special types (e.g. long binary data).Security (reduces danger of SQL injection).
![Page 22: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/22.jpg)
Prepared Statements
Example:Class.forName(myDriverName);
Connection con=DriverManager.getConnection(myDbUrl, “john”, “secret”);
PreparedStatement stmt=con.prepareStatement(“insert into EMPLOYEE values(?,?)”);
stmt.setString(1, “john”);
stmt.setDouble(2, 12000);
stmt.executeUpdate();
stmt.setString(1, “paul”);
stmt.setDouble(2, 15000);
stmt.executeUpdate();
…
… // close resources
Class.forName(myDriverName);
Connection con=DriverManager.getConnection(myDbUrl, “john”, “secret”);
PreparedStatement stmt=con.prepareStatement(“insert into EMPLOYEE values(?,?)”);
stmt.setString(1, “john”);
stmt.setDouble(2, 12000);
stmt.executeUpdate();
stmt.setString(1, “paul”);
stmt.setDouble(2, 15000);
stmt.executeUpdate();
…
… // close resources
param # 1
param # 2
Fill in params
![Page 23: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/23.jpg)
Callable Statement
Let us demonstrate:Defining a stored procedure through java (vender-specific). Invoking a stored procedure.Note: not all drivers support these features.
![Page 24: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/24.jpg)
Callable Statement
Defining a stored procedure/function.Vendor-specific code.Connection con= …
Statemenet stmt=con.createStatement();
String str=“create function countNames (empName VARCHAR) RETURN NUMBER “ +
“ IS cnt NUMBER “ +
“BEGIN “ +
“select count(*) INTO cnt from EMPLOYEE where name=empName “ +
“return cnt; “ +
“END countNames” ;
stmt.executeUpdate(str);
Connection con= …
Statemenet stmt=con.createStatement();
String str=“create function countNames (empName VARCHAR) RETURN NUMBER “ +
“ IS cnt NUMBER “ +
“BEGIN “ +
“select count(*) INTO cnt from EMPLOYEE where name=empName “ +
“return cnt; “ +
“END countNames” ;
stmt.executeUpdate(str);
![Page 25: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/25.jpg)
Callable Statement
Invoking a Stored Function, Using CallableStatement:
CallableStatement cs= con.prepareCall( “{?=call SALES.countNames (?)}" );
cs.registerOutParameter(1, Types.INTEGER);
cs.setString(2, ‘john’);
cs.execute();
System.out.println( cs.getInt(1));
CallableStatement cs= con.prepareCall( “{?=call SALES.countNames (?)}" );
cs.registerOutParameter(1, Types.INTEGER);
cs.setString(2, ‘john’);
cs.execute();
System.out.println( cs.getInt(1));
Param #1 :Out, integer
Param #2:In, String
![Page 26: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/26.jpg)
Advanced FeaturesMany features were added to the JDBC standard (currently JDBC 4.0)
http://java.sun.com/products/jdbc/download.html
There are other (competing or complementary) technologies:
JDOEntity EJB’sHibernateMore…
![Page 27: JDBC Tutorial - courses.cs.tau.ac.il](https://reader030.vdocuments.site/reader030/viewer/2022012812/61c2a75f0d033b5c9e18930f/html5/thumbnails/27.jpg)
References
Some slide content borrowed from
http://java.sun.com/docs/books/tutorial/jdbc/basics/index.html
http://otn.oracle.co.kr/admin/seminar/data/otn-jdbc.ppt
http://notes.corewebprogramming.com/student/JDBC.pdf