简体   繁体   中英

Java MySQL executeUpdate syntax error

Here's the code:

try{
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM mytable WHERE array=\"" + arrayName + "\"");
        if(rs.next()){
            String values = rs.getString("values");
            if(values == null) values = "";
            values += " " + added;
            values = values.replaceAll("\\s+"," ");
            stmt.executeUpdate("UPDATE mytable SET values = \"" + values + "\" WHERE array = \"" + arrayName + "\"");
            return true;
        }else{
            System.out.println("Missing array '" + arrayName + "', returning false");
            return false;
        }
    } catch(SQLException e) {
        String error = "MySQL crash while adding to array " + arrayName + "\n";
        error += e.getMessage();
        System.out.println(error);
        return false;
    }

Parameters of note: "mytable" is the name of the table in my database, "added" is the string I'm looking to add to a string in the "values" column of mytable, and "arrayName" is the string already stored in the "array" column of mytable ("array" and "values" are the only columns). Here's the error I'm getting:

MySQL crash while adding to array anodematerialsoptions
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'values = "item1 item2 item3 added" WHERE array = "arrayName"' at line 1

So the "stmt.executeQuery" worked fine, and the "stmt.executeUpdate" failed on a syntax error. Can someone point out what is wrong here?

values is a reserved word in pretty much ANY sql database. You'll have to escape it:

        stmt.executeUpdate("UPDATE mytable SET `values` = \""  etc...
                                               ^------^---note the backticks

And note that you're vulnerable to sql injection attacks .

You can use the query with alias in mysql

change

  stmt.executeUpdate("UPDATE mytable SET values = \"" + values + "\" WHERE array = \"" + arrayName + "\"");

into

  stmt.executeUpdate("UPDATE mytable t SET t.values = \"" + values + "\" WHERE t.array = \"" + arrayName + "\"");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM