Java 如何使用JDBC在SELECT查询中使用动态表名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21664925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use dynamic table name in SELECT query using JDBC
提问by Nawaz
I have 5 or table table to query from \
我有 5 个或表要从 \ 查询
my syntax i like this
我的语法我喜欢这个
String sql2 = "SELECT * FROM ? WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql2);
System.out.println("SQL before values are set "+sql2);
System.out.println("The values of table/test name recieved in TestPrint stage 1 "+tblName);
System.out.println("The values of test name recieved in TestPrint stage 1 "+key);
// values are outputted correctly but are not getting set in the query
pst.setString(1, tblName);
pst.setLong(2, key);
ResultSet rs2 = pst.executeQuery(sql2);
while(rs2.next()){
String ID = rs2.getString("ID");
jLabel35.setText(ID);
jLabel37.setText(ID);
jLabel38.setText(ID);
// them print command is initiated to print the panel
}
The problem is when i run this i get an error saying ".....you have and error in SQL syntax near ? WHERE Patient_ID = ?"
问题是当我运行它时,我收到一条错误消息“.....你在附近的 SQL 语法中有错误?WHERE Patient_ID = ?”
When i output the sql using system.out.println(sql2);
当我使用 system.out.println(sql2); 输出 sql 时;
values are not set in sql2
值未在 sql2 中设置
采纳答案by Mureinik
When you prepare a statement, the database constructs an execution plan, which it cannot do if the table is not there. In other words, placehodlers can only be used for values, not for object names or reserved words. You'd have to rely on Java to construct your string in such a case:
当你准备一条语句时,数据库会构造一个执行计划,如果表不存在,它就无法执行。换句话说,占位符只能用于值,不能用于对象名称或保留字。在这种情况下,您必须依靠 Java 来构造字符串:
String sql = "SELECT * FROM `" + tblName + "` WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql);
pst.setLong(1, key);
ResultSet rs = pst.executeQuery(sql);