如何在Query语言中编写变量?

时间:2015-04-25 16:54:01

标签: java

示例:

String s1;
String q = "select * from EntryByTitle where booktitle='"+s1+"'";

这里在查询语句中为什么在语法中使用+ s1 +。因为s1是字符串,所以它应该是'“s1”'。但为什么'+ s1 +''写在项目中。

1 个答案:

答案 0 :(得分:1)

使用PreparedStatement和绑定参数。这通常采用

形式
String q = "select * from EntryByTitle where booktitle=?";
String bookTitle = "";
Connection conn = null;
try {
    try (PreparedStatement ps = conn.prepareStatement(q)) {
        ps.setString(1, bookTitle);
        try (ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                System.out.println(rs.getString("booktitle"));
            }
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}