如何在java jdbc中查询字符串

时间:2016-03-22 05:40:46

标签: java jdbc

我得到的是异常

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?http://www.andhrabhoomi.net/' at line 1

我正在尝试检查数据库中是否存在字符串

我的代码:

               sql = "SELECT url FROM data where url = ?"+ "string";
                ResultSet rs = statement.executeQuery(sql);
                System.out.println(rs); 

2 个答案:

答案 0 :(得分:2)

由于您确实有?参数标记,因此您可能会尝试使用PreparedStatement,并假设"string"是实际的已清理示例?所用的值。

这是PreparedStatement的完成方式:

String sql = "SELECT url FROM data where url = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
    stmt.setString(1, "string");
    try (ResultSet rs = stmt.executeQuery()) {
        while (rs.next()) {
            System.out.println(rs.getString("url"));
        }
    }
}

答案 1 :(得分:0)

在试用版

上应用此功能
ps = conn.prepareStatement("SELECT url FROM data WHERE url = '?' + string");
ps.setString(1, THE VARIABLE ON WHERE YOU ARE GETTING THE VALUE OF URL);
rs = ps.executeQuery();