Java Programming: Java Data Base Connectivity
Java Programming: Java Data Base Connectivity
Java Programming: Java Data Base Connectivity
Agenda
Introduction to JDBC Establishing Connection Executing Query Process Result Callable Statement
Objectives
At the end of this module, you will be able to: Explain how to connect to a database using Java Database Connectivity (JDBC). Create and execute a query using JDBC API. Analyze how to use the Metadata objects to retrieve more information about the database or the result set. Know the function of commit and roll back in transactions.
Introduction to JDBC
Introduction to JDBC
JDBC is an API that helps a programmer to write java programs to connect to any database, retrieve the data from the database. java.sql package contains a set of interfaces that specify the JDBC API
Connect
Query
Process results
Close
Stage 1: Connect
Connect
Query
Process results
Close
Establishing Connection
jdbc:<subprotocol>:<subname>
Protocol Subprotocol
Database identifier
jdbc:oracle:<driver>:@<database>
Executing Query
Stage 2: Query
Connect
Query
Create a statement
Process results
Close
1. To execute SQL statement , we should first create Statement object, as: Statement stmt = conn.createStatement();
Process Result
Connect
Process results
Close
while (rset.next()) { String name = rset.getString(NAME"); String supervisor = rset.getString(SUPERVISOR"); // Process or display the data
}
Example (Contd.).
class TestConnection{ public static void main(String args[] ) { new MakeDatabaseConnection(); } }
Quiz
1. To load a driver into the memory ____________ method is used.
Do not use a primitive type when your query might return a SQL null
Use ResultSet.wasNull() to determine whether a column has a null value
Close Connection
Connect
Close
This object provides more than 100 methods to obtain information about the database
1.
DatabaseMetaData dbmd = conn.getMetaData(); String s1 = dbmd getURL(); String s2 = dbmd.getSQLKeywords(); boolean b1 = dbmd.supportsTransactions(); boolean b2 = dbmd.supportsSelectForUpdate();
Example
import java.sql.*; public class MetaDataEx { public static void main(String s[]) { try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connectioncon=DriverManager.getConnection("jdbc:odbc:mdsn" ,"scott","tiger"); DatabaseMetaData dbmd = con.getMetaData(); String s1 = dbmd.getURL(); System.out.println(s1); String s2 = dbmd.getSQLKeywords(); System.out.println(s2); boolean b1 = dbmd.supportsTransactions(); System.out.println(b1); boolean b2 = dbmd.supportsSelectForUpdate(); System.out.println(b2); Statement st=con.createStatement();
Example (Contd.).
ResultSet rset=st.executeQuery("select ename,empno,sal,comm from emp"); ResultSetMetaData rsmd = rset.getMetaData(); System.out.println(rsmd.getColumnCount()); for (int i = 1; i <= rsmd.getColumnCount(); i++) { String colname = rsmd.getColumnName(i); System.out.println(colname); String coltype = rsmd.getColumnTypeName(i); System.out.println(coltype); } con.close(); } catch(Exception e1){System.out.println(e1); } } }
Type
NUMBER DATE
SUPERVISOR
VARCHAR2
PreparedStatement pstmt = conn.prepareStatement("update STUDENT set SUPERVISOR = ? where ID = ?"); PreparedStatement pstmt = conn.prepareStatement("select SUPERVISOR from STUDENT where ID = ?");
PreparedStatement pstmt = conn.prepareStatement("update STUDENT set SUPERVISOR = ? Where ID = ?"); pstmt.setString(1, "OUT"); pstmt.setInt(2, id); pstmt.executeUpdate();
Example
import java.sql.*; public class PreparedStEx { private Connection con; private PreparedStatement pstmt; public PreparedStEx() { try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:krishna"); st=con.createStatement(); st.executeUpdate("create table test (name char(25), id int)"); String data[][]={{"Ford","100"},{"Arthur","110"},{"Trillian","120"}, {"Zaphod","130"}}; pstmt=con.prepareStatement("insert into test(name,id) values(?,?)"); for(int i=0;i<data.length;i++){
Example (Contd.).
pstmt.setString(1,data[i][0]); pstmt.setInt(2,Integer.parseInt(data[i][1])); pstmt.executeUpdate(); } pstmt.close(); con.close(); }catch(Exception e) { e.printStackTrace(); } } public static void main(String[]a ) { PreparedStEx t=new PreparedStEx(); } }
Callable Statement
When the stored procedure returns, computed values (if any) are retrieved through the CallableStatement object
Example
import java.sql.*; public class ProcedureCall { public static void main(String args[]) { try{ Class.forName("oracle.jdbc.driver.OracleDriver "); Connection con=DriverManager.getConnection(jdbc:odbc:mds n","scott","tiger"); CallableStatement cstmt = con.prepareCall("{call " +"addnumbers" + "(?,?,?)}"); cstmt.registerOutParameter(3,Types.INTEGER); cstmt.setInt(1,Integer.parseInt(args[0])); cstmt.setInt(2,Integer.parseInt(args[1])); cstmt.execute();
Example (Contd.).
System.out.println(cstmt.getInt(3)); con.close(); }catch(Exception e) { System.out.println(e); } } }
Using Transactions
With JDBC drivers: New connections are in autocommit mode Use conn.setAutoCommit(false) to turn autocommit off To control transactions when you are not in autocommit mode: conn.commit(): Commit a transaction conn.rollback(): Roll back a transaction
con=DriverManager.getConnection("Jdbc:Odbc:emp","",""); stmt = con.createStatement(); int i=stmt.executeUpdate("create table pradeep(empno integer,ename varchar(20),deptno integer)"); } catch(Exception e) { System.out.println(e); } } }
Quiz
1. _____ method is used for PreparedStatement Object. 2. _________ method is used changed for auto commit mode. 3. _______ method is used for call a stored procedure from JDBC.
DriverManager
Connection
DatabaseMetaData
Statement
ResultSet
ResultSetMetaData
Summary
In this module, you were able to: Explain how to connect to a database using Java Database Connectivity (JDBC). Create and execute a query using JDBC API. Analyze how to use the Metadata objects to retrieve more information about the database or the result set. Know the function of commit and roll back in transactions.
References
1. Armstrong, E., Ball and others (2005). The J2EETM1.4 tutorial. Retrieved March 9, 2012, from, http://java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html 2. Oracle (2012). JDBC Basics. Retrieved March 9, 2012, from http://java.sun.com/docs/books/tutorial/jdbc/basics/index.html
Thank You