0

I am having difficulty with the following statement that I want to send to the MySQL server:

UPDATE abonament SET ? = '1' WHERE abonutid = ?

And I replace them with:

ps.setString(1, "`" + (indexLunaPlatita + 1) + "`");
ps.setInt(2, selVal);

But when I run the program I get this into MySQL:

''`24`' = '1' WHERE abonutid = 2'

So it automatically surrounds the back ticked expression with ' '.

Any help please ?

Thank you !

Dragonthoughts
  • 2,180
  • 8
  • 25
  • 28

1 Answers1

2

You cannot use placeholders (?) for column names, just for values. This is a general rule (not limited to MySQL).

If you need to determine column name based on user input, be very careful - you'll have to sanitize the input to avoid SQL Injection attack yourself, JDBC can't help you prevent the attack in this case.


The reason for ? not being viable for your case is because those parameterized queries are implemented using prepared statements:

  • A statement is sent to database, parsed, compiled and possibly optimized without the values being known at this time
    • (primary use case intended for prepared statements is performance improvements through reuse of the compiled statement)
  • The values are then provided in second step, instructing the database to perform the statement with those values
  • Another set of values then may be sent to execute the prepared statement with, etc.

Since the values are not sent until the second step, they cannot be used for anything that determines what the statement really does (e.g. which table or columns it uses).

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43