Java JDBC PreparedStatements中的高级参数化
在PreparedStatement中是否有参数化表的方法Java JDBC PreparedStatements中的高级参数化,java,jdbc,Java,Jdbc,在PreparedStatement中是否有参数化表的方法 select * from ? where id=? 如果没有,那么最好的方法是什么?或者,有没有其他方法可以做到这一点而不失去准备好的报表的优势 select * from ? where id=? 谢谢。我们可以用以下方法 "select * from "+table_name+" where id=?"; PreparedStatement允许您仅在where子句中提供动态查询参数使用占位符代替表名,然后将其替换为表名 S
select * from ? where id=?
如果没有,那么最好的方法是什么?或者,有没有其他方法可以做到这一点而不失去准备好的报表的优势
select * from ? where id=?
谢谢。我们可以用以下方法
"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);
简而言之,不能在准备好的语句中参数化表名。您必须使用字符串连接来构造sql。基本上准备好的语句用于列值,而不是表名 我能想到的最好方法是使用
string.format
如下:
String sql = String.format("select * from $1%s", yourtable);
如果您的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");
检查
更多信息。@CPUTerminator,让我们再次阅读OP的帖子,什么是最好的方法,或者,有没有其他方法可以做到这一点而不失去准备声明的优势?在上述方法中,没有人会失去事先准备好的声明的优势