简体   繁体   中英

SQL database update statement not working

ResultSet rs = stat.executeQuery("select * from donor where username = '" +       username + "'");
        String type = rs.getString("bloodtype");
        System.out.println("the user's blood type is: " + type);
        String Updatesentence = "update bank set " + type +  " = " + type + " + 1 where name = '" + name + "'";
        System.out.println(Updatesentence);
        stat.executeUpdate(Updatesentence);

Guys I am trying to make an update to an SQL database with this code and although I am not getting an error somewhere the code does not work with the desired result. The

            System.out.println(Updatesentence);

is not printed and the update is not performed. I know there probably is somewhat of a syntax error on my String declaration, but I cannot work it out.

You have this:

String Updatesentence = "update bank set " + type + " = " + type + " + 1 where name = '" + name + "'";

So if the user's blood type is AB...

update bank set AB = AB + 1 where name = 'JohnSmith'

And that obviously won't work. You need to indicate the column in the database you want to be updating.

One of the most important things you need to remember when writing SQL statements, is to separate the query literal from the query arguments . This allows protection from SQL Injection and also makes it possible for the DB to reuse the query with different arguments (and "hard parsing" / optimizing the query only once). The way you do this with JDBC, is through prepared statements :

try (PreparedStatement queryPS = myConnection.prepareStatement(
        "select * from donor where username = ?");
     PreparedStatement updatePS = myConnection.prepareStatement(
        "update bank set bloodtype = ? where name = ?");) {

    queryPS.setString(1, username);
    ResultSet rs = queryPS.executeQuery();
    if (rs.next()) {
        String type = rs.getString("bloodtype");
        System.out.println("the user's blood type is: " + type);
        updatePS.setString(1, type);
        updatePS.setString(2, username);
        updatePS.executeUpdate();
    }
} catch (SQLException e) {
    // handle it
}

When you use prepared statements, you don't need to worry about concatenating the inputs into the query; they will be sanitized and injected automatically. If you're doing things the "wrong way", it's really easy to make a mistake when you construct the query piece by piece from different variables in your code, and this is exactly what happened with the misplaced type variable in your example.

Your update statement is wrong. It should be : String Updatesentence = "update bank set bloodtype = " + type + " + 1 where name = '" + name + "'" ;

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