我正在使用PreparedStatement
至insert
进入mysql,当我 checkin mysql console
时,我没有收到任何错误,但数据尚未插入。它说Empty set
:
public void insertGeometryValues(String gisuniqkey,String objkey,String objtype,String geometry)
{
PreparedStatement statement=null;
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY, GEOMETRY,OBJTYPE,OBJKEY) values(?,?,?,?);";
try {
conn.setAutoCommit(false);
statement=(PreparedStatement) conn.prepareStatement(sql);
statement.setString(1, gisuniqkey);
statement.setString(2,geometry);
statement.setString(3,objtype);
statement.setString(4,objkey);
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我还尝试使用 Statement
像这样并得到这个ERROR
try {
if(conn==null)
{
System.out.println("The connection was not initialized.");
return false;
}
Statement st=(Statement) conn.createStatement();
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY, GEOMETRY,OBJTYPE,OBJKEY) values('"+gisuniqkey+"','"+geometry+"','"+objtype+"',"+objkey+"');";
System.out.println(sql);
rc=st.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
最佳答案
您对PreparedStatement的使用从未真正执行该语句。将代码更改为:
public void insertGeometryValues(String gisuniqkey,String objkey,String objtype,String geometry) {
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY, GEOMETRY,OBJTYPE,OBJKEY) values(?,?,?,?);";
conn.setAutoCommit(false);
try (PreparedStatement statement = conn.prepareStatement(sql)) {
statement.setString(1, gisuniqkey);
statement.setString(2,geometry);
statement.setString(3,objtype);
statement.setString(4,objkey);
statement.executeUpdate(); // <---- This is what is missing!
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我还添加了 try-with-resources,以便该语句实际上正确关闭。
关于java - 使用Prepared插入MySQL数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22938817/