在Java中将变量添加到sql语句中

时间:2011-03-21 04:48:22

标签: java sql

我正在尝试在java中编写一个sql语句,该语句在where子句中使用字符串变量。我尝试了多种方法来做到这一点,但它一直告诉我,我没有使用正确的语法。有人可以告诉我正确的方法吗?此查询中的变量是par_id。

  

String sql2 =“SELECT * FROM Tennis1294966077108.container_tbl WHERE parent_id = +”'par_id'“+ ORDER BY creation_time asc”;

4 个答案:

答案 0 :(得分:11)

使用PreparedStatement

PreparedStatement ps = connection.prepareStatement("SELECT * FROM Tennis1294966077108.container_tbl WHERE parent_id = ? ORDER BY creation_time asc");
ps.setObject(1, par_id);

答案 1 :(得分:0)

PreparedStatement ps = connection.prepareStatement(
    "SELECT * FROM Tennis1294966077108.container_tbl " +
    "WHERE parent_id = ? ORDER BY creation_time asc");
ps.setInt(1, par_id); 

答案 2 :(得分:0)

String sql2 = "SELECT * FROM Tennis1294966077108.container_tbl WHERE parent_id='"+par_id+"'
ORDER BY creation_time asc";

答案 3 :(得分:-1)

尝试:

"SELECT * FROM Tennis1294966077108.container_tbl WHERE parent_id = '" 
+ par_id 
+ "' ORDER BY creation_time asc";