我有一个程序,可以从给定的表和列字符串的数据库中进行选择。
public void selectAllFrom(String table, String column){
String sql = "SELECT ? FROM ?";
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql)){
pstmt.setString(1, column);
pstmt.setString(2, table);
ResultSet rs = pstmt.executeQuery();
while (rs.next()){
System.out.println(rs.getString(column));
}
} catch (SQLException e){
System.out.println(" select didn't work");
System.out.println(e.getMessage());
}
}
由于某种原因,它不起作用,但它会捕获
这也是 connect() 函数:
private Connection connect(){
Connection conn = null;
// SQLite connection string
String url = "jdbc:sqlite:C:/sqlite/db/chinook.db";
try{
// creates connection to the database
conn = DriverManager.getConnection(url);
System.out.println("Connection to SQLite has been established");
} catch (SQLException e){
System.out.println(e.getMessage());
System.out.println("Connection didn't work");
}
return conn;
}
我知道问题不在于数据库,因为我可以在没有参数的情况下运行其他选择查询。这是给我带来问题的参数。谁能告诉我问题出在哪里吗?
最佳答案
表名或列名不能用作PreparedStatement 的参数。它必须是硬编码的。
String sql = "SELECT " + column + " FROM " + table;
您应该重新考虑设计,以使这两个常数保持不变并对列值进行参数化。
关于java - 带参数的 SQLite 查询在 Java 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41373232/