简体   繁体   English

如何在Java中使用变量执行SQL语句

[英]How to execute a SQL statement in Java with variables

I have the following mysql statement to delete records from a DB that is working. 我有以下mysql语句从正在运行的数据库中删除记录。

SET @email = 'delete@mailinator.com';
SET @userID = (SELECT id FROM USER WHERE email = @email);
DELETE FROM user_role_group WHERE user_id = @userID;
DELETE FROM user_client_setup WHERE user_id = @userID;
DELETE FROM USER WHERE id = @userID;

I want to run this same query in Java with a jdbc mysql connection. 我想使用jdbc mysql连接在Java中运行相同的查询。 I have tried the following 我尝试了以下

public void deleteCoreUser(String email) {
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection con=DriverManager.getConnection(
                    "jdbc:mysql://db.com:3306/core","username","password");
            Statement stmt=con.createStatement();
            ResultSet rs=stmt.executeQuery("SET @email = '"+email+"';\n" +
                    "SET @userID = (SELECT id FROM user WHERE email = @email);\n" +
                    "DELETE FROM user_role_group WHERE user_id = @userID;\n" +
                    "DELETE FROM user_client_setup WHERE user_id = @userID;\n" +
                    "DELETE FROM user WHERE id = @userID;");
            con.close();
            System.out.println("Deleting user "+email+" from the Core DB");
        }catch(Exception e){ System.out.println(e);}
    }

I am getting this error when running 运行时出现此错误

java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; java.sql.SQLSyntaxErrorException:您的SQL语法有错误; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SET @userID = (SELECT id FROM user WHERE email = @email); 检查与您的MariaDB服务器版本相对应的手册以获取正确的语法,以在'SET @userID =(从用户WHERE email = @email中选择SELECT ID)附近使用; DELETE FROM user_role_' at line 2 从第2行的user_role_'删除

Use execute() instead of executeQuery() since it returns multiple ResultSet. 使用execute()而不是executeQuery(),因为它返回多个ResultSet。 See answer ( Statement.execute(sql) vs executeUpdate(sql) and executeQuery(sql) ) and add ?allowMultiQueries=true to the database url "jdbc:mysql://db.com:3306/core?allowMultiQueries=true" 请参阅答案( Statement.execute(sql)与executeUpdate(sql)和executeQuery(sql) ),然后将?allowMultiQueries = true添加到数据库URL "jdbc:mysql://db.com:3306/core?allowMultiQueries=true"

I suspect the issue is due to the allowMultiQueries flag in MariaDB. 我怀疑问题是由于MariaDB中的allowMultiQueries标志所致。 This defaults to false , meaning each query is essentially run in a vacuum and your SET @userID = (SELECT id FROM user WHERE email = @email); 默认为false ,这意味着每个查询本质上都是在真空中运行的,而您的SET @userID = (SELECT id FROM user WHERE email = @email); query doesn't know what @email is. 查询不知道@email是什么。 To resolve this with you current code, set the database allowMultiQueries=true . 要使用当前代码解决此问题,请设置数据库allowMultiQueries=true

If the MySQL queries are running correctly in MySQL console, then there is no reason that same query will show syntax error when handling it with jdbc . 如果MySQL查询在MySQL控制台中正确运行,则没有理由使用jdbc处理同一查询时将显示语法错误。 You are making mistakes in implementing the queries with java and how java handles it. 您在使用Java实现查询以及Java如何处理查询时犯了错误。

public void deleteCoreUser(String email) {
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://db.com:3306/core","username","password");
        Statement stmt = con.createStatement();
        String sql = "SET @email = '" + email + "'";
        stmt.execute(sql);
        sql = "SET @userID = (SELECT id FROM USER WHERE email = @email)";
        stmt.execute(sql);
        sql = "DELETE FROM user_role_group WHERE user_id = @userID";
        stmt.execute(sql);
        sql = "DELETE FROM user_client_setup WHERE user_id = @userID";
        stmt.execute(sql);
        sql = "DELETE FROM USER WHERE id = @userID";
        stmt.execute(sql);
        con.close();
        System.out.println("Deleting user " + email + " from the Core DB");
    } catch(Exception e){ System.out.println(e);}
}

stmt.executeQuery is used when you try to get resultset from the queries. 当您尝试从查询中获取结果集时,将使用stmt.executeQuery But in this case you are not asking for resultset. 但是在这种情况下,您不需要的是结果集。 That's why no Resultset is necessary and only stmt.execute should work. 这就是为什么没有Resultset是必要的,只有stmt.execute应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Java执行多个SQL语句? - How to execute multiple SQL statement using Java? Statement.execute(SQL) JDBC java - Statement.execute(SQL) JDBC java 我该如何做一个IF语句来比较分配给1类中2个字符串变量的2个整数,然后在Java中的另一个类中执行代码? - How do I make an IF statement that compares 2 integers assigned to 2 string variables in 1 class then execute the code in another class in Java? Java Derby SQL查询语句使用变量 - Java Derby SQL query statement using variables 在JAVA中使用SQL语句的where子句中的变量 - Using variables in where clause of SQL statement in JAVA Java-to-sql语句,Insert into vs setString中的变量 - Java - to - sql statement, variables in Insert into vs setString 转义 Java 变量以将 SQL 语句序列化为字符串 - Escaping Java variables to serialise SQL statement to string 使用java.sql.Statement执行多行sybase语句 - Execute Multiline sybase statement with java.sql.Statement 如何使用变量作为WHERE执行SQL语句? - How to execute a SQL statement with a variable as WHERE? 如何在Java中的where in子句中的单个变量中执行具有多个值的SQL语句 - How to execute a SQL statement in Java with many values in a single variable in where in clause
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM