Ok, for short:
All JDBC commands in try-blocks - for the best use one own try-catch for each command:// Load driver class
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
// Connect - DSN is "myDSN", user is "myUser", password is "myPW"
Connection Con = DriverManager.getConnection(
"jdbc:odbc:myDSN", "myUser", "myPW" );
// Execute a Select
Statement st = Con.createStatement();
ResultSet rs = st.executeQuery( "select id, name from tab where id < 100" );
// Loop over all records
while( rs.next() )
{
// Read actual record
int id = rs.getInt( 1 );
String name = rs.getString( 2 );
// Test output
System.println( "id = " + id );
System.println( "name = '" + name + "'" );
}
// next select
rs = st.executeQuery( "select ..." );
...
// recommended: close statement
st.close();
// Disconnect
con.close();
If you catch the exceptions ascatch( SQLException e )
, you can print out more informations like DB error code etc.
Look at the methods of SQLException.
Hi,
Could you tell me what is the difference between :
your proposal :
// Load driver classClass.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );// Connect - DSN is "myDSN", user is "myUser", password is "myPW"Connection Con = DriverManager.getConnection( "jdbc:odbc:myDSN", "myUser", "myPW" );
and this proposal :
this servlet FindNames ...
String queryString = "select FIRST_NAME, LAST_NAME from EMPLOYEE_INFO where FIRST_NAME like '" +
f_name +
"%' and LAST_NAME like '" +
l_name +
"%'";
try
{
///Build and execute query
ODBCConnect SQL = new ODBCConnect();
ResultSet rset;
SQL.setDSN("Activity3");
SQL.setSQLString(queryString);
rset = SQL.select();
.... calling this ODBCConnect class, with this method:
public static ResultSet select()
throws SQLException
{
DriverManager.registerDriver(new "sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection (DBName, "training", "training");
stmt = conn.createStatement();
return stmt.executeQuery(queryString);
}
Question :
- is
DriverManager.registerDriver(new "sun.jdbc.odbc.JdbcOdbcDriver");
equal to
ClassForName("sun.jdbc.odbc.JdbcOdbcDriver")
?
Thanks for your help.
Regards
Hugues