【发布时间】:2017-05-13 09:31:31
【问题描述】:
我有一个程序可以从给定表和列字符串的数据库中进行选择。
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;
}
我知道问题不在于数据库,因为我能够在没有参数的情况下运行其他选择查询。是参数给我带来了问题。谁能告诉我是什么问题?
【问题讨论】:
-
很好奇......当@Gurwinder Singh 建议的那样将变量直接放入 SQL 字符串要容易得多时,你为什么还要费心去经历所有这些混乱。
标签: java sql database sqlite database-connection