【发布时间】:2015-04-28 10:58:45
【问题描述】:
是否可以在 PreparedStatement 中对表格进行参数化?
select * from ? where id=?
如果没有,最好的方法是什么?或者,有没有其他方法可以在不失去 PreparedStatement 优势的情况下做到这一点?
谢谢。
【问题讨论】:
是否可以在 PreparedStatement 中对表格进行参数化?
select * from ? where id=?
如果没有,最好的方法是什么?或者,有没有其他方法可以在不失去 PreparedStatement 优势的情况下做到这一点?
谢谢。
【问题讨论】:
简短的回答是您不能在准备好的语句中参数化表名。您必须使用字符串连接来构造 sql。基本上准备好的语句用于列值而不是表名。
我能想到的最好的方法就是像这样使用string.format:
String sql = String.format("select * from $1%s", yourtable);
【讨论】:
我们可以这样做
"select * from "+table_name+" where id=?";
PreparedStatement 允许您仅在 where 子句中提供动态查询参数
【讨论】:
使用占位符代替表名,然后将其替换为您的表名。
String strQuery = "INSERT INTO $tableName (col1, col2)
VALUES (?,?);";
当你知道表名时替换如下:
String query =strQuery.replace("$tableName",tableName);
stmt =connection.prepareStatement(query);
【讨论】:
String table_name= // get tablename
String sql= "select * from" +table_name+" where id=?";
【讨论】:
如果您的 PreparedStatement 带有您所说的 SQL 查询,您可以这样做:
int yourID = 1;
String tablename = "table";
String query = "SELECT * FROM " + tableName + " where id = ?";´
PreparedStatement statement = con.prepareStatement(query);
statement.setInt(1, yourID);
它将用1 替换?。如果您有多个?,您可以设置类似
statement.setString(2, "YourString");
检查 http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html 了解更多信息。
【讨论】: