我正在尝试使用Java和MySQL更新表格,但我对这个表格感到满意。
Java可以运行更新查询,但不会提交到数据库。
这是我打电话的方法:
public int qryUpdateRegistry(int registryId, Registry registry) throws SQLException {
PreparedStatement qry = null;
Connection conn = null;
Boolean okayToUpdate = false;
try {
conn = connectToDatabase();
if (registry.getHostId() != 0 && registry.getRegistryName() != null && registry.getEventDate() != null) {
okayToUpdate = true;
}
if (okayToUpdate) {
String strSql = "UPDATE registry SET host_id = ?, registry_name = ?, registry_guest_pw = ?, registry_event_date = ?, registry_auto_delete_yn = ?, registry_num_days_delete = ? WHERE registry_id = ?";
qry = conn.prepareStatement(strSql);
qry.setInt(1, registry.getHostId());
qry.setString(2, registry.getRegistryName());
qry.setString(3, registry.getRegistryPassword());
qry.setDate(4, registry.getEventDate());
qry.setInt(5, registry.getRegistryAutoDelete());
qry.setInt(6, registry.getNumDaysDelete());
qry.setInt(7, registryId);
qry.executeUpdate();
}
} catch (Exception e) {
e.printStackTrace();
return 500;
} finally {
if (qry != null) {
qry.close();
}
if (conn != null) {
conn.close();
}
}
return 200; // Server response that it was updated
}
但是在数据库上没有任何改变。我没有SQL异常,没有任何错误。
奇怪的是,这个以完全相同的方式完成的更新查询在Java端完全正常。
public int qryUpdateHostPassword(int hostId, String password)
throws Exception {
PreparedStatement qry = null;
Connection conn = null;
Boolean okayToInsert = false;
try {
conn = connectToDatabase();
if (hostId != 0 && password != null) {
okayToInsert = true;
}
if (okayToInsert) {
qry = conn
.prepareStatement("UPDATE host SET password = ? WHERE host_id = ?");
qry.setString(1, password);
qry.setInt(2, hostId);
qry.executeUpdate();
}
} catch (Exception e) {
e.printStackTrace();
return 500; // Server error
} finally {
if (qry != null) {
qry.close();
}
if (conn != null) {
conn.close();
}
}
return 200; // Server response that it was inserted
}
有什么可能导致数据库无法更新的想法?
答案 0 :(得分:0)
问题在于我在另一个类中调用的路径参数。 它运行正常,但总是尝试使用registry_id为0来更新记录;
@Path("/reg/{registryID}")
应该是:
@Path("/reg/{registryId}")
当然,当我使用时:
@PathParam("registryId") int registryId
所以int registryId
总是0;
当我查看它试图使用的ID时,我才注意到它。
答案 1 :(得分:-1)
我唯一能想到的是你有autoCommit假。
connectToDatabase()
是什么?
无论如何你可以这样做:
conn = connectToDatabase();
conn.setAutoCommit(true);
或者只是确认在使用autoCommit创建连接时不要将其设为false