如果提供的值存在,我想获取PK记录。如果不是我想插入提供的值并获得自动递增的主键。我做的是:
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);
}
和方法executeQuery定义:
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;
}
如果是,为什么我会得到一个java.sql.SQLException:在开始结果集之前 在
// created now we want the ID of the new market
rs=executeQuery(sql);
id =rs.getInt("id");//<<<<-----Exception Here
System.out.println("ID"+id);