0

I have a few Prepared statement that are doing the same thing but on different table:

ReportImageWrongLang = con.prepareStatement("INSERT INTO userReportedWrongLang VALUES (?,?,?) ON DUPLICATE KEY UPDATE UserId=UserID");
ReportImageProhibited = con.prepareStatement("INSERT INTO userReportedImages VALUES (?,?,?) ON DUPLICATE KEY UPDATE UserId=UserID");

ReportElse = con.prepareStatement("INSERT INTO Reportelse VALUES (?,?,?) ON DUPLICATE KEY UPDATE UserId=UserID");

I'm calling this statement according to some event on my java program.

I want to change this 3 statement into one statement:

Report = con.prepareStatement("INSERT INTO ? VALUES (?,?,?) ON DUPLICATE KEY UPDATE UserId=UserID");

and to set the first parameter to be the table name (Report.setString (1,tableName))

but i'm getting this error:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''userreportedimages' VALUES ('3',331,1) ON DUPLICATE KEY UPDATE UserId=UserID' at line 1

Is there any way to do it?

Jocelyn
  • 11,209
  • 10
  • 43
  • 60
Shai Zarzewski
  • 1,638
  • 3
  • 19
  • 33

1 Answers1

0

You can't parameterise SQL identifiers, such as table or column names.

However, you could write a Java function which takes the table or column name as an argument and concatenates it into an SQL string. Be careful to ensure that it is sanitised in order to prevent SQL injection attacks, though.

That said, needing to do something like this is often an indication of a badly de-normalised schema. Multiple tables with the same structure often can (and should) be combined into a single table with a column that indicates whatever differs between the two.

eggyal
  • 122,705
  • 18
  • 212
  • 237