-1
String SQL_UPDATE = "UPDATE `club_juvenil` SET "+SET_MySQL+" = "+nuevo_valor.getText().toString()+" WHERE dni_competidor = "+wher_combo.getSelectedItem().toString()+" ";

Hi. I'm trying to update a table on MySQL using Java, but I get the error Unknown column '(value from wher_combo)' in 'where clause' I'm trying to use a variable in the SET value to switch from one to other column(which is the main reason I decided to do it this way), but then the WHERE seems like it is reading the wher_combo value as a column, and obviously lends to an error because that column doesn't exist on the table.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Danilo
  • 35
  • 4
  • 2
    Your code is vulnerable to SQL injection. Please use prepared statements with parameters instead of concatenating values into a query string like this. – Mark Rotteveel Jun 14 '21 at 10:10

2 Answers2

1

Assuming that SET_MySQL is a valid column in that table, then the statement should work with quoted strings, as user3088799 already answered.

Please note however that appending unknown data directly to the SQL query string like this is highly dangerous and should never be done. You can read about prepared statements here, which provide a safe way of passing arbitrary data as parameters.

See also How does the SQL injection from the “Bobby Tables” XKCD comic work? and Java - escape string to prevent SQL injection

F0X
  • 370
  • 4
  • 13
  • Is good to know. I noticed every possible solution used the prepared statements but wasn't sure why and how to handle the multiple options with the JComboBox and the prepared statements. I will read more about that, thank you. – Danilo Jun 14 '21 at 10:14
  • @Danilo you can simply set any string as a parameter, which seems like what you where doing anyways. – F0X Jun 14 '21 at 10:20
  • @user15793316 yes, if it his 101% certain that the value's can only be from some set of strings defined in the source code then it would theoretically be fine, but in practice this is most likely not the case and even if it where you should still use prepared statements (not to mention the performance aspect of things). – F0X Jun 14 '21 at 10:32
  • @user15793316 oh that is what you meant, of course you cannot add actual SQL via parameters, as that's what they're supposed to prevent. – F0X Jun 14 '21 at 10:38
0

It looks like you forgot quote. Like this, can you try ? :

" WHERE dni_competidor = '"+wher_combo.getSelectedItem().toString()+"' ";
user3088799
  • 147
  • 7
  • It works now, seems it didn't work the first time I tried as I used '"+SET_MySQL+"' and got an error then removed the '' for every variable and got this one, but your solutions works! Thank you – Danilo Jun 14 '21 at 10:10