在java中执行查询不返回结果但在mysql workbench中仍然返回结果

时间:2014-08-25 06:59:06

标签: java mysql jdbc

此查询:

    SELECT 
    r.report_id,
    r.user_id,
    u.user_name,
    u.user_mail,
    d.department_name,
    r.report_comment,
    r.report_target_date,
    r.report_create_date,
    r.report_revised_date,
    r.report_root_id,
    report_revised_id
FROM
    report r
        JOIN
    user u ON u.user_id = r.user_id
        JOIN
    department d ON u.department_id = d.department_id
        JOIN
    authority a ON r.user_id = a.user_src_id
        AND a.user_dest_id = 131
WHERE
    r.report_target_date BETWEEN '2014-07-23 23:59:00' AND '2014-08-22 00:00:00'
    AND r.report_comment LIKE '%事務%'

在mysql工作台中,此查询具有返回值,但在java中使用它时,它不会返回任何内容:

Statement stmt = connection.createStatement(); 
ResultSet rs = null;
rs = stmt.executeQuery(query);

在mysql workbench中,此查询具有返回值,但rs return为空。

1 个答案:

答案 0 :(得分:2)

您将日语字符传递给查询。这可能很容易成为字符编码问题。

使用PreparedStatement并通过setString()调用插入值,该调用将正确处理编码。

修改您的query以获得参数(以问号标记):

...
WHERE
    r.report_target_date BETWEEN '2014-07-23 23:59:00' AND '2014-08-22 00:00:00'
    AND r.report_comment LIKE ?

Java代码:

PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, "%事務%"); // Parameter index is 1-based
ResultSet rs = ps.executeQuery();