首页 > 解决方案 > 尝试使用准备好的语句删除元组

问题描述

我正在尝试使用用户输入从属性歌曲中删除一个元组,但我收到一条错误消息,说 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();
        }

    }

标签: javamysqldatabase

解决方案


字符串必须用引号括起来,如下所示:

        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();

推荐阅读