|
|
|
|
|
|
|
|
|
|
|
|
|
|
JAVA JDBC
Objectives
What Is JDBC?
Duel with the database
JDBC versus ODBC and other API
JDBC ENVIRONMENT STEPS INVOLVED in JDBC
STEP 1:- Configuring the JDBC Case 1: JDK 1.1.1 and above , no need. (JDBC, JDBC-ODBC Package are included with the JDK kit). Case 2: JDK 1.02, Get the driver from JavaSoft JDBC. Configuring the JDBC-ODBC Bridge Install JDBC-ODBC Bridge Install ODBC Driver Configure ODBC STEP 2:- Connecting to Database. Invoke the JDBC Package import java.sql.*; Load the Application Driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Create a database URL String url="jdbc:odbc:dsn"; Assign the user ID and password String user="guest"; String pwd="guest"; Open a Connection Connection con=DriverManager.getConnection(url,user,pwd) (Throw SQLException) Other Settings con.AutoCommit(true); Transaction are automatically committed when executed.con.setReadOnly(true);
Step 3: Create a SQL statement.
Statement stmt = con.createStatement(); (Throws SQLException) String query="Select * from table_name"; Step 4: Execute the SQL Statement ResultSet rs=stmt.executeQuery(query); (Throws SQLException) Step 5: Process the results of SQL statement.
boolean found=rs.next(); rs.getInt(column number or field name); rs.getString(column number or field name); rs.getDate(column number or field name); rs.getTime(column number or field name);
Step 6: Commit or rollback the transaction con.commit(); con.rollback();
Step 7: Close the resultset. rs.close();
Step 8: Close statement. stmt.close();
Step 9: Close the connection. con.close();
JDBC: Calling a Stored Procedures
Steps for calling the Procedures or function Call Create the Command with Placeholders: // Stored procedure call String command = "{call PROCEDURENAME(?,?,?,?)}"; // 4 placeholders // Stored function call String command = "{? = call FUNCTIONNAME(?, ?, ? , ?)}"; // 4 placeholders + 1 return value
Create a Callable Statement Object CallableStatement cstmt = con.prepareCall (command); (Throws a SQLException error.) Register the IN and OUT Placeholders // Assign IN parameters (use positional placement) cstmt.setInt(1, 50); // first placeholder has an integer value of 50 cstmt.setString(2, "Smith"); // second placeholder has a string value of "Smith" cstmt.registerOutParameter(3, Types.NUMERIC); //NUMERIC is preferred over INTEGER with some databases cstmt.registerOutParameter(4, Types.VARCHAR); // fourth placeholder is an OUT field of type VARCHAR. (Throws a SQLException error.)
Execute the Procedure or Function Call cstmt.execute(); (Throws a SQLException error.)
Process the OUT Placeholders BigDecimal num = cstmt.getBigDecimal(3,0); String str = cstmt.getString(4); (Throws a SQLException error.)
Close the CallableStatement Object // Close the call object after update is complete cstmt.close(); (Throws a SQLException error.)
Accessing Metadata
What is metadata? It is descriptive information about database structure and connections. e.g.
Syntax : DatabaseMetaData dmeta=con.getMetaData(); ResultsetMetaData rsmeta=rs.getMetaData();
CLIENT-SERVER DESIGN CONSIDERATION
Two-Tier Model
Advantages
Disadvantages
Three Tier Model using CGI Advantages
Disadvantages
Summary
Sample Code : (Using JDBC-ODBC Bridge) import java.sql.*; class Sample { static Connection con; // database connection object /** Main routine */ Public static void main(String args[]) throws Exception { // Load the JDBC-ODBC bridge driver Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); // Open the database and display all rows in a table open(); insert(); select(); // Add a new row and show the result insert(); //select("WHERE EmpCode = 11"); // Update a row and commit the result update(true); select("WHERE EmpCode = 11"); // Update a row and rollback the result update(false); select("WHERE EmpCode = 100"); // Delete a row and show the result delete(); select("WHERE EmpCode = 100"); // Close the database close(); } /** Open a database connection */ static void open() throws SQLException { // ODBC data source name where db4 is the database name // It is a MsAccess database file. String dsn = "jdbc:odbc:db4"; String user = "guest"; String password = ""; // Connect to the database con = DriverManager.getConnection(dsn, user, password); // Shut off autocommit con.setAutoCommit(false); } /** Commit all pending transactions and close the database connection */ static void close() throws SQLException { con.commit(); con.close(); } /** Issue a SQL query with a WHERE clause */ static void select(String whereClause) throws SQLException { Statement stmt; // SQL statement object String query; // SQL select string ResultSet rs; // SQL query results boolean more; // "more rows found" switch query = "SELECT Empcode, name " + "FROM table1 "; stmt = con.createStatement(); rs = stmt.executeQuery(query); // Check to see if any rows were read more = rs.next(); if (!more) { System.out.println("No rows found."); return; } // Loop through the rows retrieved from the query while (more) { System.out.println("ID: " + rs.getInt("EmpCode")); System.out.println("Name: " + rs.getString("Name")); System.out.println(""); more = rs.next(); } rs.close(); stmt.close(); } /** Issue a SQL query without a WHERE clause */ static void select() throws SQLException { select(""); } /** Insert a new row */ static void insert() throws SQLException { Statement stmt; // SQL statement object String sql; // SQL insert command int rows; // Number of rows inserted sql = "INSERT INTO Table1 " + "VALUES (11, 'Gaurav')"; stmt = con.createStatement(); rows = stmt.executeUpdate(sql); con.commit(); stmt.close(); System.out.println(rows + " row(s) added"); } /** Update a new row */ static void update(boolean commit) throws SQLException { Statement stmt; // SQL statement object String sql; // SQL update command int rows; // Number of rows inserted String title; // New title for the update if (commit) title = "Arun"; else title = "Aniesh"; sql = "UPDATE Table1 " + "SET Name='" + title + "' " + "WHERE EmpCode = 2"; stmt = con.createStatement(); rows = stmt.executeUpdate(sql); if (commit) con.commit(); else con.rollback(); stmt.close(); System.out.println(rows + " row(s) updated"); } /** Delete a row */ static void delete() throws SQLException { Statement stmt; // SQL statement object String sql; // SQL delete command int rows; // Number of rows inserted sql = "DELETE FROM Table1 " + "WHERE EmpCode = 11"; stmt = con.createStatement(); rows = stmt.executeUpdate(sql); con.commit(); stmt.close(); System.out.println(rows + " row(s) deleted"); } }
|
|
||||||||
|
|
||||||||||
|
|
||||||||||
|
|
||||||||||
|
|