Search code examples
javamysqljdbcprepared-statement

Java SQL Prepared Statement Update not working


I have the problem that I just can't get the following code to run. I've tried and changed all of them but I always get an error, maybe you have an idea where the error is?

public class TestCommand implements ServerCommand{

    @Override
    public void performcommand(SlashCommandInteractionEvent event, Member m, MessageChannelUnion channel,
            VoiceChannel ec, VoiceChannel pub, TextChannel log, Guild guild) {

        Connection connection = null;
        PreparedStatement preparedStatement = null;
                
        String sql = ("UPDATE member_ships SET?= ? WHERE UUID= ?"); 
        
        try {
            connection = MySQL.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,"Cyclone");
            preparedStatement.setInt(2,9);
            preparedStatement.setLong(3,316931131188576123l);
            preparedStatement.executeUpdate();
        }   catch (SQLException e) {
            e.printStackTrace();
        } finally {
            MySQL.closePreparedStatement(preparedStatement);
            MySQL.closeConnection(connection);
        }
    }
}

The MySQL class

public class MySQL {

    public static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection("jdbc:mysql://*****","***","****");
        connection.setAutoCommit(true);
        System.out.println("Database connecion successful"); //TODO Remove 
        return connection;
    }

And here the error stacktrace:

java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''Cyclone'= 9 WHERE UUID= 316931131188576123' at line 1
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
        at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
        at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:916)
        at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1061)
        at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1009)
        at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1320)
        at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:994)

Solution

  • You can't bind obejct names (in this case, a column name), only values.

    Having said that, since all the values here seem to be hard-coded, you really don't need a PreparedStamtement, and could just execute the statement directly:

    con.executeUpdate("UPDATE member_ships SET Cyclone = 9 WHERE UUID = 316931131188576123l");