Wel Come: Dhiraj Thakkar (
Wel Come: Dhiraj Thakkar (
JDBC
• Introduction to Java Class.
• A Simple java ‘Hello World’ application.
• Introduction to JDBC.
• Type of Drivers (Type 1, Type 2, Type 3, Type 4)
• JDBC Classes for creating a Connection
• Connection Troubles.
• Class Not Found
• Driver Not Found
• Basic Database Access
• Eclipse 3.0 or up
• J2sdk 1.5
• Toad (Interface to oracle)
• Tomcat 5.0
• Dream Weaver(JSP,HTML)
Compilation
# javac HelloWorld.java
results in HelloWorld.class
Execution
# java HelloWorld
Hello World
java.lang.*
All classes/items in “lang” package of java package.
System is really the java.lang.System class.
This class has a public static field called out
which is an instance of the java.io.PrintStream
class. So when we write System.out.println(),
we are really invoking the println() method of
the “out” field of the java.lang.System class.
Package Statement
Import Statements
Interface Statements
Class Declarations
Two-tier
Three-tier
N-tier
higher complexity
higher maintenance
lower network efficiency
more parts to configure (and buy)
X/OPEN
ODBC JDBC
Type I: “Bridge”
Type II: “Native”
Type III: “Middleware”
Type IV: “Pure”
Type I ODBC
ODBC
“Bridge” Driver
Type II
JDBC CLI (.lib)
“Native”
Type IV
“Pure”
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Type 1 Drivers
JDBC-ODBC Bridges
JDBC driver translates call into ODBC and
redirects ODBC call to an ODBC driver on
the DBMS
ODBC binary code must exist on every
client
Translation layer compromises execution
speed to small degree
Diagram
jdbc.drivers=com.oracle.jdbc.OracleDriver:etc;
or programatically:
String old = sysProps.getProperty(“jdbc.drivers”);
drivers.append(“:” + oldDrivers);
sysProps.put(“jdbc.drivers”, drivers.toString());
eg: jdbc:sybase:Tds:limousin:4100/myDB
DELETE
if( genericStmt.execute(SQLString)) {
else {
}
etc.
getXXX(columnName/indexVal)
getFloat()
getInt()
getDouble()
eg:
PreparedStatement ps = conn.prepareStatement(“update table
Then execute:
int count = ps.executeUpdate();
next
Isolated: A transaction is encapsulated and unmodifiable until
conn.commit();
conn.rollback();
start over
Example:
catch( SQLException e) {
try {
conn.rollback();
} catch (SQLException e) { checkPlease(); }
}
Sybase’s Transact-SQL
Sybase Example:
create proc sp_select_min_bal
(@balance real)
as
select account_id
where balance > @balance
return
conn.prepareCall(“{call sp_setBalance(?,?)}”
stmt.registerOutParameter(2, Types.FLOAT);
stmt.setInt(1, custID);
stmt.setFloat(2, 213432.625);
stmt.execute();
Float newBalance = stmt.getFloat(2);
Always register OUT or INOUT parameters in stored
procedures using registerOutParameter()
Connecting to a DB
Db=DriverManager.getConnection(url, usr,
pwd);
No DB specification (the driver has been loaded and
will be selected by the DriverManager regarding url).
URL syntax:
Jdbc:postgresql:database
Jdbc:postgresql://host/dabase
Jdbc:postgresql://host:port/dabase
Jdbc:postgresql:database?user=me
Jdbc:postgresql:database?user=me&password=mypass
setAutoCommit();
Transaction mode
Rollback();
Commit();
PreparedStatement
CreateStatement
St = db.createStatement();
St.executeUpdate(« sql code »);
St.executeQuery(« sql code »);
St.execute(« sql code »);
St.addBatch(« sql statement »);
St.executeBatch();
Etc.
import java.sql.*;
class JdbcTest {
public static void main (String args []) throws SQLException {
// Load Oracle driver
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
updateStud.setString(1, “John”);
updateStud.setString(2, “Smith”);
updateStud.executeUpdate();
String getString(int columnIndex)
String getString(String columnName)
conn.setAutoCommit(false);
....
transaction
...
con.commit();
con.setAutoCommit(true);
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Using Transactions
example
con.setAutoCommit(false);
PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES
SET SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 50);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal = con.prepareStatement( "UPDATE COFFEES
SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Retrieving Exceptions
JDBC lets you see the warnings and exceptions generated by your DBMS
and by the Java compiler. To see exceptions, you can have a catch block
print them out. For example, the following two catch blocks from the sample
code print out a message explaining the exception:
try {
// Code that could generate an exception goes here.
// If an exception is generated, the catch block below
// will print out information about it.
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
Comment
<%-- Comment --%>
Expression
<%= java expression %>
Scriplet
<% java code fragment %>
Include
<jsp:include page="relativeURL" />
<%
try {
// Load Oracle Driver class file
DriverManager.registerDriver
(new oracle.jdbc.driver.OracleDriver());
<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
Iteration Code
<%
}
%>
</table> Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - First Attempt
conn.setAutoCommit(false);
pstmt.setInt(1,Integer.parseInt(request.getParameter("SSN")));
pstmt.setString(2, request.getParameter("ID"));
…
pstmt.executeUpdate();
conn.commit();
conn.setAutoCommit(true);
}
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Second Attempt
Presentation Code
<table>
<tr>
<th>SSN</th>
<th>First</th>
<th>Last</th>
<th>College</th>
</tr>
Insert Form Code
<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
Iteration Code
<%
}
%>
</table> Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Second Attempt
Insert Form Code
<tr>
<form action="students.jsp" method="get">
<input type="hidden" value="insert" name="action">
<th><input value="" name="SSN" size="10"></th>
<th><input value="" name="ID" size="10"></th>
<th><input value="" name="FIRSTNAME" size="15"></th>
<th><input value="" name="LASTNAME" size="15"></th>
<th><input value="" name="COLLEGE" size="15"></th>
<th><input type="submit" value="Insert"></th>
</form>
</tr>
conn.setAutoCommit(false);
pstatement.setString(1, request.getParameter("ID"));
pstatement.setString(2, request.getParameter("FIRSTNAME"));
…
int rowCount = pstatement.executeUpdate();
conn.setAutoCommit(false);
conn.setAutoCommit(true);
}
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Third Attempt
Delete Code
// Check if a delete is requested
if (action != null && action.equals("delete")) {
conn.setAutoCommit(false);
pstmt.setInt(1,
Integer.parseInt(request.getParameter("SSN")));
int rowCount = pstmt.executeUpdate();
conn.setAutoCommit(false);
conn.setAutoCommit(true);
}
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Third Attempt
Presentation Code
<table>
<tr>
<th>SSN</th>
<th>First</th>
<th>Last</th>
<th>College</th>
</tr>
Insert Form Code
<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
Iteration Code
<%
}
%>
</table> Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Entry Form - Third Attempt
Iteration Code
<tr>
<form action="students.jsp" method="get">
<input type="hidden" value="update" name="action">
<td><input value="<%= rs.getInt("SSN") %>" name="SSN"></td>
<td><input value="<%= rs.getString("ID") %>" name="ID"></td>
…
<td><input type="submit" value="Update"></td>
</form>
<form action="students2.jsp" method="get">
<input type="hidden" value="delete" name="action">
<input type="hidden" value="<%= rs.getInt("SSN") %>" name="SSN">
<td><input type="submit" value="Delete"></td>
</form>
</tr>
• System-wide data
–
connection.getMetaData().getDatabaseProductName()
–
connection.getMetaData().getDatabaseProductVersion()
• Table-specific data
– resultSet.getMetaData().getColumnCount()
• When using the result, remember that
the index starts at 1, not 0
– resultSet.getMetaData().getColumnName()
• executeQuery
– Executes the SQL query and returns the data in a table
(ResultSet)
– The resulting table may be empty but never null
ResultSet results =
statement.executeQuery("SELECT a, b FROM table");
• executeUpdate
– Used to execute for INSERT, UPDATE, or DELETE
SQL statements
– The return is the number of rows that were affected in the
database
– Supports Data Definition Language (DDL) statements
CREATE TABLE, DROP TABLE and ALTER TABLE
int rows =
statement.executeUpdate("DELETE FROM EMPLOYEES" +
"WHERE STATUS=0");
Dhiraj Thakkar (MS-IT ,SE- J2EE Applications)
Useful Statement Methods
execute
– Generic method for executing stored procedures and
prepared statements
– Rarely used (for multiple return result sets)
– The statement execution may or may not return a
ResultSet (use statement.getResultSet). If the return value
is true, two or more result sets were produced
• getMaxRows/setMaxRows
– Determines the maximum number of rows a
ResultSet may contain
– Unless explicitly set, the number of rows is unlimited
(return value of 0)
• getQueryTimeout/setQueryTimeout
– Specifies the amount of a time a driver will wait for a
STATEMENT to complete before throwing a
SQLException
• Idea
– By default, after each SQL statement is executed the
changes are automatically committed to the database
– Turn auto-commit off to group two or more
statements
together into a transaction
connection.setAutoCommit(false)
– Call commit to permanently record the changes to the
database after executing a group of statements
– Call rollback if an error occurs
Transactions: Example
Connection connection =
DriverManager.getConnection(url, username, passwd);
connection.setAutoCommit(false);
try {
statement.executeUpdate(...);
statement.executeUpdate(...);
connection.commit();
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException sqle) {
// report problem
}
} finally {
try {
connection.close();
} catch (SQLException sqle) { }
}
(for Transactions)
• getAutoCommit/setAutoCommit
– By default, a connection is set to auto-commit
– Retrieves or sets the auto-commit mode
• commit
– Force all changes since the last call to commit to become
permanent
– Any database locks currently held by this Connection
object are released
• rollback
– Drops all changes since the previous call to commit
– Releases any database locks held by this Connection
object
CallableStatement cs = con.prepareCall("{call
SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
SQL Server
Datetime: 1/300th second
Oracle
Date: 1 second
Timestamp: 1/100 millionth second
SQL Server
select a=deptid, b=deptname,c=empno
from dept;
Oracle
select deptid a, deptname b, empno c
from dept;
http://www.ss64.com/orasyntax/datatype
s.html
You can have more than one LOB column in a table, whereas you
are restricted to just one LONG or LONG RAW column per table.
When you insert into a LOB, the actual value of the LOB is stored
in a separate segment (except for in-line LOBs) and only the LOB
locator is stored in the row, thus making it more efficient from a
storage as well as query perspective. With LONG or LONG RAW,
the entire data is stored in-line with the rest of the table row.