//NOTE -- this code will not compile, but that's on purpose.
import java.sql.*;
...
public static int testdbcode(Connection conn) {
//Prepare the statement
PreparedStatement s = conn.prepareStatement(
"select id from test_table where name = ?");
//Set the parameters
s.setString(1, "fred");
//Run the query
ResultSet rs = s.executeQuery()
//Move to the first result row
rs.next();
//Get the answer (first result parameter)
int id = rs.getInt(1);
return id;
}
...
import java.sql.*;
...
public static int testdbcode(Connection conn) {
try {
//Prepare the statement
PreparedStatement s = conn.prepareStatement(
"select id from test_table where name = ?");
//Set the parameters
s.setString(1, "fred");
//Run the query
ResultSet rs = s.executeQuery()
//Move to the first result row
rs.next();
//Get the answer (first result parameter)
int id = rs.getInt(1);
return id;
} catch (Exception e) {
//Put error handling code here
return -1;
}
}
...