We will use the Connection, Statement, and ResultSet objects. The steps are as follows:
Declare the variables.
Instantiate the Connection object.
Open the Connection.
Instantiate the Statement object.
Instantiate the Recordset object
Open the Recordset
Process the records
Close the Recordset, Statement, and Connection
Set the objects to null
Additionally, we need to import the java.sql package.
The code would look like this:
[][]
<%@ page import="import java.sql.*" %>
<%
Connection con = null;
Statement stm = null;
ResultSet rst = null;
String cls = "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:";
String sql = "";
try {
Class.forName(cls);
con = DriverManager.getConnection(url);
stm = con.createStatement();
sql = "";
rst = stm.executeQuery(sql);
while (rs.next()) {
//Processing goes here
}
rst.close();
stm.close();
con.close();
}
catch (ClassNotFoundException cnfe) {
out.println(cnfe.toString());
}
catch (SQLException sqle) {
out.println(sqle.toString());
}
finally {
rst = null;
stm = null;
con = null;
}
%>
[
][
]
A few notes on the code:
Where you see , replace that with the actual Data Source Name you created in an earlier lesson.
Where you see , replace that with either an SQL Select statement or the name of a table or select query in the database. You still need the double-quotes around it, but not the angle brackets.
Setting your objects to null at the end helps speed up the process of freeing the memory.