我使用一个非常简单的删除查询“DELETE FROM S WHERE SNO =”+ row;
虽然在运行时我得到错误但是在输入我想要删除S1时没有列S1存在?
我100%确定我在数据库中有S1。
错误:
java.sql.SQLException:[SQLITE_ERROR] SQL错误或缺少数据库(没有这样的列:S1)
我的删除方法:
public void Delete() throws SQLException, ClassNotFoundException {
String query = "";
//asks the user for a tablename.
String tablename = JOptionPane.showInputDialog("Which table do you want to delete from?");
String row = JOptionPane.showInputDialog("Which row do you want to delete?");
// checks if the input is equal to any of these names and changes the query thereafter.
switch (tablename) {
case "S":
query = "DELETE FROM S WHERE SNO="+row;
break;
case "J":
query = "DELETE FROM J WHERE JNO ="+row;
break;
case "P":
query = "DELETE FROM P WHERE PNO ="+row;
break;
case "SPJ":
query = "DELETE FROM SPJ WHERE SNO ="+row;
break;
case "s":
query = "DELETE FROM S WHERE SNO ="+row;
break;
case "j":
query = "DELETE FROM J WHERE JNO ="+row;
break;
case "p":
query = "DELETE FROM P WHERE PNO ="+row;
break;
case "spj":
query = "DELETE FROM SPJ WHERE SNO ="+row;
break;
}
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(query);
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
System.out.println("You have deleted from " + tablename + " where rowID = " + row);
}
答案 0 :(得分:0)
在SQL中,字符串用引号分隔:
query = "DELETE FROM x WHERE xNO = '" + row + "'";
如果没有引号,单词将被解释为表名或列名。
无论如何,为避免格式化问题(当字符串包含引号时)并避免SQL注入攻击,最好使用参数:
query = "DELETE FROM x WHERE xNO = ?";
...
PreparedStatement ps = c.prepareStatement(query);
ps.setString(1, row);
rs = ps.executeQuery();