0

I have a connection with MySQL database like this

preparedStatement = conn.prepareStatement("Select name, id FROM club WHERE ? > 0")
preparedStatement.setString(1, obj.getVisit);

I am getting the error MySQL server version for the right syntax to use near 'WHERE 'visit' > 0 ' at line 1.

How do I passed in dynamic column name for this?

EDIT I have 4 different column names for this hence I needed it to be dynamic.*

Deviprasad Sharma
  • 470
  • 1
  • 8
  • 19
whatanoob
  • 11
  • 1
  • Formatting your question will increase the visibility and it will make the question more understandable. You can make use of various markdown syntax to format your code and errors. [Visit Here](https://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks) for more details on formatting. – Sourav Sep 14 '20 at 16:22

2 Answers2

0

The only way to achieve this is to dynamically populate query string.

String query = "Select name, id FROM club WHERE "+ columnNamee + " > 0";

The reson to this in the first place to prevent SQL injection, so that any string parameter value is quoted by default.

GiorgosDev
  • 1,757
  • 1
  • 14
  • 16
0

Why not build statement as a string?

String column = obj.getVisit()// get column you want to query 
String query = String.format("Select name, id FROM club WHERE %s > 0", column);
preparedStatement = conn.prepareStatement(query)
Rony Nguyen
  • 1,067
  • 8
  • 18