在MySQL列中匹配空字符串,而不是空值

时间:2015-10-01 15:57:14

标签: mysql jdbc

我无法获得正确的语法 - 我尝试将列匹配为空字符串,而不是null。我尝试使用单双引号来区分字符串。

containerRefNo = "\"\"";

ps = getConnection().prepareStatement(
                "delete from  inumber_join where container_no = ?");

我收到的错误是

  

您的SQL语法有错误;查看与您的MariaDB服务器版本对应的手册,以便在inumber_join附近使用正确的语法,其中container_no =''''''

1 个答案:

答案 0 :(得分:1)

使用参数化查询时,您不需要在参数值中包含任何分隔符。简单地使用ps.setString(1, "");对我来说很好。

即......

// setup
try (Statement st = conn.createStatement()) {
    st.executeUpdate(
            "CREATE TEMPORARY TABLE inumber_join_temp (" +
                "id INT AUTO_INCREMENT, " +
                "container_no VARCHAR(10) NULL, " +
                "PRIMARY KEY (id)" +
            ")");
    st.executeUpdate(
            "INSERT INTO inumber_join_temp (container_no) " +
                "VALUES (null), (''), (null), (''), (null)");
}

// test
String sql = 
        "SELECT COUNT(*) AS n " +
        "FROM inumber_join_temp " +
        "WHERE container_no = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setString(1, "");  // search for empty string
    try (ResultSet rs = ps.executeQuery()) {
        rs.next();
        System.out.println(rs.getInt(1));
    }
}

...返回

2