Using Prepared Statements to set Table Name

后端 未结 7 1826
生来不讨喜
生来不讨喜 2020-11-22 11:57

I\'m trying to use prepared statements to set a table name to select data from, but I keep getting an error when I execute the query.

The error and sample code is di

相关标签:
7条回答
  • 2020-11-22 12:27

    This is technically possible with a workaround, but very bad practice.

    String sql = "IF ? = 99\n";
    sql += "SELECT * FROM first_table\n";
    sql += "ELSE\n";
    sql += "SELECT * FROM second_table";
    PreparedStatement ps = con.prepareStatement(sql);
    

    And then when you want to select from first_table you set the parameter with

    ps.setInt(1, 99);
    

    Or if not, you set it to something else.

    0 讨论(0)
提交回复
热议问题