JDBC PreparedStatements 中的高级参数化
Advanced parametrization in JDBC PreparedStatements
是否有参数化 PreparedStatement 中的 table?
select * from ? where id=?
如果不是,最好的方法是什么,或者有没有其他方法可以在不失去 PreparedStatement 优势的情况下做到这一点?
谢谢。
我们可以按照以下方式进行
"select * from "+table_name+" where id=?";
PreparedStatement 仅允许您在 where 子句中提供动态查询参数
使用占位符代替 table 姓名,然后将其替换为您的 table 姓名。
String strQuery = "INSERT INTO $tableName (col1, col2)
VALUES (?,?);";
并在您知道 table 名称时替换如下:
String query =strQuery.replace("$tableName",tableName);
stmt =connection.prepareStatement(query);
String table_name= // get tablename
String sql= "select * from" +table_name+" where id=?";
简短的回答是您不能在准备好的语句中参数化table名称。您必须使用字符串连接构造 sql 。基本上准备好的语句用于列值而不是 table 名称。
我能想到的最好的方法是这样使用 string.format
:
String sql = String.format("select * from %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");
检查
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html 获取更多信息。
是否有参数化 PreparedStatement 中的 table?
select * from ? where id=?
如果不是,最好的方法是什么,或者有没有其他方法可以在不失去 PreparedStatement 优势的情况下做到这一点?
谢谢。
我们可以按照以下方式进行
"select * from "+table_name+" where id=?";
PreparedStatement 仅允许您在 where 子句中提供动态查询参数
使用占位符代替 table 姓名,然后将其替换为您的 table 姓名。
String strQuery = "INSERT INTO $tableName (col1, col2)
VALUES (?,?);";
并在您知道 table 名称时替换如下:
String query =strQuery.replace("$tableName",tableName);
stmt =connection.prepareStatement(query);
String table_name= // get tablename
String sql= "select * from" +table_name+" where id=?";
简短的回答是您不能在准备好的语句中参数化table名称。您必须使用字符串连接构造 sql 。基本上准备好的语句用于列值而不是 table 名称。
我能想到的最好的方法是这样使用 string.format
:
String sql = String.format("select * from %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");
检查 http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html 获取更多信息。