Intoduction to JDBC (Java Database Connectivity-- Connecting to DBMS) Oracle JDBC Tutorial & Documentation http://docs.oracle.com/javase/tutorial/jdbc/basics/ Connector-J, MySql JDBC Driver Documentation, https://dev.mysql.com/doc/connector-j/5.1/en/ JDBC Drivers Java supports four types of JDBC drivers JDBC-ODBC bridge plus ODBC driver: Java code access ODBC native binary drivers, ODBC driver accesses databases, ODBC drivers must be installed on each client Native-API partly-java driver: Java code accesses database specific native binary drivers JDBC-Net pure Java driver: Java code accesses database via DBMS-independent net protocol Pure Java driver In a pure Java-based driver that communicates directly with vendor's database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself. This kind of driver is extremely flexible; you don't need to install special software on the client or server. Further, these drivers can be downloaded dynamically. 1
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols, database vendors usually supply type 4 drivers. The JDBC API is comprised of two packages: java.sql javax.sql The JDBC Interfaces Driver Connection Connection Statement Statement Statement Statement ResultSet ResultSet ResultSet ResultSet Developing JDBC Programs 2
Statement to load a driver: Class.forName("JDBCDriverClass"); A driver is a class. For example: Database Driver Class Source Access sun.jdbc.odbc.jdbcodbcdriver Already in JDK MySQL com.mysql.jdbc.driver Oracle oracle.jdbc.driver.oracledriver Connection connection = DriverManager.getConnection(databaseURL); Database Access MySQL Oracle URL Pattern jdbc:odbc:datasource jdbc:mysql://hostname/dbname jdbc:oracle:thin:@hostname:port#:oracledbsid Examples: For Access: Connection connection = DriverManager.getConnection ("jdbc:odbc:examplemdbdatasource"); For MySQL: Connection connection = DriverManager.getConnection ("jdbc:mysql://localhost/test"); For Oracle: Connection connection = DriverManager.getConnection ("jdbc:oracle:thin:@company.com:1521:orcl", "bob", "feiner"); Creating statement: Statement statement = connection.createstatement(); Executing statement (for update, delete, insert): statement.executeupdate ("create table Temp (col1 char(5), col2 char(5))"); Executing statement (for select): // Select the columns from the Student table ResultSet resultset = statement.executequery ("select firstname, mi, lastname from Student where lastname " + " = 'Smith'"); Executing statement (for select): // Select the columns from the Student table ResultSet resultset = stmt.executequery ("select firstname, mi, lastname from Student where lastname " + " = 'Smith'"); Processing ResultSet (for select): 3
// Iterate through the result and print the student names while (resultset.next()) System.out.println(resultSet.getString(1) + " " + resultset.getstring(2) + ". " + resultset.getstring(3)); Queries executeupdate Use for INSERT, UPDATE, DELETE or SQL that return nothing executequery Use for SQL (SELECT) that return a result set execute Use for SQL that return multiple result sets Uncommon ResultSet ResultSet - Result of a Query - JDBC returns a ResultSet as a result of a query - A ResultSet contains all the rows and columns that satisfy the SQL statement - A cursor is maintained to the current row of the data - The cursor is valid until the ResultSet object or its Statement object is closed - next() method advances the cursor to the next row - You can access columns of the current row by index or name 4
ResultSet has getxxx methods that: has either a column name or column index as argument returns the data in that column converted to type XXX getobject - An alternative to the getxxx method Rather than ResultSet tablelist = gettables.executequery("select * FROM name"); String firstname = tablelist.getstring( 1); - Can use ResultSet tablelist = gettables.executequery("select * FROM name"); String firstname = (String) tablelist.getobject( 1); getobject( int k) returns the object in the k th column of the current row getobject( String columnname) returns the object in the named column PreparedStatement The PreparedStatement interface is designed to execute dynamic SQL statements and SQLstored procedures with IN parameters. These SQL statements and stored procedures are precompiled for efficient use when repeatedly executed. Statement pstmt = connection.preparestatement ("insert into Student (firstname, mi, lastname) + values (?,?,?)"); Retrieving Database Metadata Database metadata is the information that describes database itself. JDBC provides the DatabaseMetaData interface for obtaining database wide information and the ResultSetMetaData interface for obtaining the information on the specific ResultSet. The DatabaseMetaData interface provides more than 100 methods for getting database metadata concerning the database as a whole. These methods can be divided into three groups: for retrieving general information, for finding database capabilities, and for getting object descriptions. The general information includes the URL, username, product name, product version, driver name, driver version, available functions, available data types and so on. Example: DatabaseMetaData dbmetadata = connection.getmetadata(); System.out.println("database URL: " + dbmetadata.geturl()); System.out.println("database username: " + dbmetadata.getusername()); 5
System.out.println("database product name: " + dbmetadata.getdatabaseproductname()); System.out.println("database product version: " + dbmetadata.getdatabaseproductversion()); System.out.println("JDBC driver name: " + dbmetadata.getdrivername()); System.out.println("JDBC driver version: " + dbmetadata.getdriverversion()); System.out.println("JDBC driver major version: " + new Integer(dbMetaData.getDriverMajorVersion())); System.out.println("JDBC driver minor version: " + new Integer(dbMetaData.getDriverMinorVersion())); System.out.println("Max number of connections: " + new Integer(dbMetaData.getMaxConnections())); System.out.println("MaxTableNameLentgh: " + new Integer(dbMetaData.getMaxTableNameLength())); System.out.println("MaxColumnsInTable: " + new Integer(dbMetaData.getMaxColumnsInTable())); connection.close(); CallableStatement The CallableStatement interface is used to execute SQL-stored procedure/function. Example: drop function if exists studentfound; delimiter // create function studentfound(first VARCHAR(20), last VARCHAR(20)) returns int begin declare result int; select count(*) into result from Student where Student.firstName = first and Student.lastName = last; return result; end; // delimiter ; 6
mysql> select studentfound('king', 'Smith'); CallableStatement callablestatement = conn.preparecall( "{? = call studentfound(?,?)}"); java.util.scanner input = new java.util.scanner(system.in); String firstname = "Jacob"; String lastname = "Smith"; callablestatement.setstring(2, firstname); callablestatement.setstring(3, lastname); callablestatement.registeroutparameter(1, Types.INTEGER); callablestatement.execute(); if (callablestatement.getint(1) >= 1) { out.println(firstname + " " + lastname + " is in the database" + "<br>"); } else { out.println(firstname + " " + lastname + " is not in the database" + "<br>"); Data Conversion 7
Some Cautions Mixing ResultSets Can't have two active result sets on same statement Connection rugby; rugby = DriverManager.getConnection( dburl, user, password); Statement gettables = rugby.createstatement(); ResultSet count = gettables.executequery("select COUNT(*) FROM name"); ResultSet tablelist = gettables.executequery("select * FROM name"); while (tablelist.next() ) System.out.println("Last Name: " + tablelist.getobject(1) + '\t' + "First Name: " + tablelist.getobject( "first_name")); // Raises java.sql.sqlexception count.getobject(1); rugby.close(); this can happen when two threads have access to the same statement Two Statements on one Connection work Connection rugby; rugby = DriverManager.getConnection( dburl, user, password); Statement gettables = rugby.createstatement(); Statement tablesize = rugby.createstatement(); ResultSet count = gettables.executequery("select COUNT(*) FROM name"); ResultSet tablelist = tablesize.executequery("select * FROM name"); while (tablelist.next() ) System.out.println("Last Name: " + tablelist.getobject(1) + '\t' + "First Name: " + tablelist.getobject( "first_name")); count.next(); System.out.println("Count: " + count.getobject(1) ); count.close(); tablelist.close(); rugby.close(); Threads & Connections - Some JDBC drivers are not thread safe - If two threads access the same connection results may get mixed up MySql driver is thread safe - When two threads make a request on the same connection - The second thread blocks until the first thread get it its results - Can use more than one connection but - Each connection requires a process on the database To run the example code from NetBeans IDE Clean/build, deploy and run 8
To see query result from collegedb, type DatabaseAccess (Servlet name) as follows. 9
10