没有主键的SQL删除为INT

时间:2013-12-11 14:46:44

标签: java sql sqlite

当我的主键是S1,S2,S3,S4等样式的文本时,如何删除?

我试图使用此查询:

Query = "DELETE FROM S WHERE SNO =" +rowID;

其中rowID是S1,S2,S3,S4等。虽然这不起作用,但如果我将主键(SNO)更改为ID号,例如1,2,3,4,5 ..然后运行它运作的查询相同吗?

完整删除代码:

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 S WHERE SNO =" + row;
                break;
            case "J":
                query = "DELETE FROM J WHERE JNO = '" + row + "'";
                break;
            case "P":
               query = "DELETE  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 SPNO = '" + row + "'";
                break;
            case "spj":
                 query = "DELETE FROM SPJ WHERE SNO = '" + row + "'";
                break;
        }
Connection c = null;

try {
  Class.forName("org.sqlite.JDBC");
  c = DriverManager.getConnection("jdbc:sqlite:test.db");
  c.setAutoCommit(false);
  System.out.println("Opened database successfully");

PreparedStatement pt=c.prepareStatement("DELETE FROM S WHERE SNO =?");
pt.setString(1,row);
pt.executeUpdate();



  c.close();

} catch ( ClassNotFoundException | SQLException e ) {
  System.err.println( e.getClass().getName() + ": " + e.getMessage() );

}
System.out.println("You have deleted from " + tablename + " where rowID = " + row);
}

2 个答案:

答案 0 :(得分:2)

使用像这样的预备陈述

PreparedStatement pt=connection.prepareStatement("DELETE FROM S WHERE SNO =?");
pt.setString(1,rowID);
pt.exeuteUpdate();

答案 1 :(得分:1)

您需要将输入放在单引号中

示例:

Query = "DELETE FROM S WHERE SNO ='" +rowID+"'";

请注意,上述查询会引入SQL Injection,而您可能会使用PreparedStatements之类的内容。