<分区>
这是我的方法:
@Override
public void deleteOneRecord(String tableName, String id) throws ClassNotFoundException, SQLException{
// Validate the parameters here.
// String sql = "DELETE FROM " + tableName + " WHERE " + column + "=" + value;
String pKeyColumnName = "";
// Statement stmt = conn.createStatement();
DatabaseMetaData dmd = conn.getMetaData();
ResultSet rs = dmd.getPrimaryKeys(null, null, tableName);
while(rs.next()){
pKeyColumnName = rs.getString("COLUMN_NAME");
System.out.println("PK column name is " + pKeyColumnName);
}
//String sql = "delete from " + tableName + " where " + pKeyColumnName + "=" + id;
String sql2 = "delete from ? where ?=?";
PreparedStatement pstmt = conn.prepareStatement(sql2);
pstmt.setString(1, tableName);
pstmt.setString(2, pKeyColumnName);
pstmt.setInt(3, Integer.parseInt(id));
pstmt.executeUpdate();
}
这是我的测试 main
:
public static void main(String[] args) throws ClassNotFoundException, SQLException {
DBStrategy db = new MySqlDBStrategy();
db.openConnection("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/book", "root", "admin");
System.out.println(db.findAllRecords("author", 0).toString());
db.deleteOneRecord("author", "2");
System.out.println(db.findAllRecords("author", 0).toString());
db.closeConnection();
}
数据库对象有效,打开连接有效,我的查找所有记录方法有效,
然后我的 deleteOneRecord
爆炸了。我收到此错误:
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''author' where 'author_id'=2' at line 1
现在我的语法没有改变,几分钟前我只是将这段代码作为 Statement
运行没问题,所以我一定是以某种方式错误地使用了 PreparedStatement
。
如有任何帮助,我们将不胜感激。