java - 尝试使用准备好的语句删除元组
问题描述
我正在尝试使用用户输入从属性歌曲中删除一个元组,但我收到一条错误消息,说
java.sql.SQLSyntaxErrorException: Unknown column 'Paragould' in 'where clause'
下面是我的代码
public static void removeSong(){
Faker faker=new Faker();
Statement stmt=null;
Connection conn=null;
Scanner in=new Scanner(System.in);
System.out.println("Which song would you like to remove?");
String songName=in.next();
String removeSongStmt="DELETE FROM allSavedSongs WHERE song="+songName+" AND userID="+currentUserID;
try {
conn=DriverManager.getConnection(DB_URL,USER,PASS);
PreparedStatement preparedStmt=conn.prepareStatement(removeSongStmt);
preparedStmt.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
解决方案
字符串必须用引号括起来,如下所示:
String removeSongStmt="DELETE FROM allSavedSongs WHERE song='"+songName+"' AND userID='"+currentUserID+"';";
编辑:这种解析非常不安全,因为字符串可能包含任何类型的垃圾。它们还可能包含那些会执行并对您造成很大伤害的 SQL 命令。您应该使用准备好的语句的强大功能,如下所示:
conn=DriverManager.getConnection(DB_URL,USER,PASS);
PreparedStatement preparedStmt=conn.prepareStatement("DELETE FROM allSavedSongs WHERE song=? AND userID=?");
preparedStmt.setString(songname);
preparedStmt.setString(currentUserID);
preparedStmt.execute();
推荐阅读
- javascript - Mongoose 使用 $or 查询日期
- regex - 是否可以使用`switch -regex`获得匹配位置
- node.js - Puppeteer 在检索 lis 之前失去上下文
- laravel - Auth::attempt 总是返回 false,即使输入和哈希正确
- python - 从多张照片中的棋盘格网格估计相机姿势时确保共享原点
- php - 如何解决“调用未定义函数 mysqli_connect()”?
- java - Android 采样频率 (Hz) 和采样周期 (µs) 之间是否存在转换因子 (HIGH_SAMPLING_RATE_SENSORS)
- javascript - Javascript 回调按顺序输出
- javascript - 声明元素而不将它们放在函数内
- python - 套接字:本地服务器端口为 .search-agent