Java mySQL删除行
我在尝试删除mySQL数据库中的一行时遇到问题 我的Java中的SQL方法是Java mySQL删除行,java,mysql,sql,Java,Mysql,Sql,我在尝试删除mySQL数据库中的一行时遇到问题 我的Java中的SQL方法是 @Override public void removeCustomerByID(int customerID) throws StorageException { try { connect(); String sq1 = "DELETE FROM Customer WHERE ID ='"+customerID+"'"; int deleteRow =
@Override
public void removeCustomerByID(int customerID) throws StorageException {
try {
connect();
String sq1 = "DELETE FROM Customer WHERE ID ='"+customerID+"'";
int deleteRow = stmt.executeUpdate(sq1);
if(deleteRow == 1) {
System.out.println("Row was deleted");
} else {
System.out.println("Row was not deleted");
}
} catch (SQLException ex)
{
throw new StorageException("Unable to get Customer", ex);
} finally
{
disconnect();
}
}
以及调用它的方法
@Test
public void testDeleteCustomer() throws StorageException {
Customer custom = new Customer("Allan", "Jensen", 12345677);
assertEquals(81, Main.db.getCustomerIDByNameAndPhone(custom));
Main.db.removeCustomerByID(custom.getCustomerID());
assertEquals(-1, Main.db.getCustomerIDByNameAndPhone(custom));
}
如您所见,当找不到客户时,我将其设置为返回-1(因此我声明它等于-1),但它仍然返回81。Main.db。是我访问数据库类并调用其方法的地方。所以您的主要问题是该行没有从数据库中删除。如果我错了,请纠正我
您可以检查一下,当您使用mysql驱动程序创建连接时,事务状态是什么。我的意思是你设置了连接。自动提交(真)。请设置这个,然后检查。我认为您的delete语句没有被提交。我不会将参数直接传递到查询中,我会将stmnt更改为PreparedStatement的类型,而不是statement。试着这样写
//You obviously have these defined somewhere
PreparedStatement pstmnt = null;
Connection con = null;
String sq1 = "DELETE FROM Customer WHERE ID = ?";
pstmnt = con.prepareStatement(sql);
pstmnt.setString(1, customerID);
pstmnt.executeUpdate();
con.commit()//If you have not set auto commit
尝试从删除查询中删除
”
,例如“从客户那里删除ID=“+customerID
,因为它是PreparedStatement
的int
+1,从而避免了一些可怕的安全问题