I want to get the PK for a record if the value provided exist. If not i want to insert the supplied value and get the auto incremented primary key. What i did is:
String sql= "SELECT id FROM markets where market = 'value';";
ResultSet rs=executeQuery(sql);
int id;
if (!rs.isBeforeFirst() ) {
//there is No record found. must be created
rs.close();
conn = DriverManager.getConnection(DB_URL,USER,PASS);
st = conn.createStatement();
String query = "INSERT INTO markets (market) VALUES('value')";
st.executeUpdate(query);
// created now we want the ID of the new market
rs=executeQuery(sql);
id =rs.getInt("id");
System.out.println("ID"+id);
rs.close();
}
else
while (rs.next()){
//the value exist, we get the ID of it
id =rs.getInt("id");
System.out.println(".."+id);
}
and method executeQuery is defined:
public static ResultSet executeQuery(String query){
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
String sql;
return stmt.executeQuery(query);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
- Is this a correct aproach?
if it is, why do i get a java.sql.SQLException: Before start of result set on
// created now we want the ID of the new market rs=executeQuery(sql); id =rs.getInt("id");//<<<<-----Exception Here System.out.println("ID"+id);