gpt4 book ai didi

java - 没有主键为 INT 的 SQL 删除

转载 作者:行者123 更新时间:2023-12-01 23:21:50 26 4
gpt4 key购买 nike

当我的主键是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);
}

最佳答案

像这样使用准备好的语句

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

关于java - 没有主键为 INT 的 SQL 删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20522153/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com