简体   繁体   English

如何在 java 中为 mysql 的 JSON 数据类型使用准备好的语句?

[英]How to use a prepared statement for JSON data types for mysql in java?

I have a JSON column that I want to create a prepared statement for, but I'm not sure how to go about it since the parameters for the statement are inside a literal string.我有一个 JSON 列,我想为其创建一个准备好的语句,但我不确定如何去做,因为该语句的参数在一个文字字符串中。

For example:例如:

PreparedStatement stmt = myConn.prepareStatement("SELECT JSON_SET(new_friends, '$.?', '[?]') from friend_list where id = ?");

for (int i = 0; i < new_friends.size(); i++) {
        String friend = new_friends.get(i);

        // not sure what to put here
        stmt.set....
        stmt.set....
        stmt.set(3, i);
}

Anyone have any suggestions?有人有什么建议吗?

? placeholders are not used like string interpolation.占位符不像字符串插值那样使用。 They replace entire parameters.它们替换整个参数。 When the function argument is a string, the entire argument must be the literal string or built with SQL string functions taking parameters as further arguments.当函数参数是字符串时,整个参数必须是文字字符串或使用 SQL 字符串函数构建,将参数作为进一步的参数。

Assuming your syntax is correct for what you want to achieve, consider these:假设您的语法对于您想要实现的目标是正确的,请考虑以下几点:

JSON_SET(new_friends, '$.?', '[?]') -- not valid
JSON_SET(new_friends, ?, ?) -- valid
JSON_SET(new_friends, CONCAT('$.',?), CONCAT('[',?,']')) -- valid

Parameter 1 would be set to the string $.foo for a query in the style of line 2 above, or foo in the style of line 3.对于上面第 2 行样式的查询,参数 1 将设置为字符串$.foo ,或第 3 行样式的foo

The reason your version isn't valid is exactly the reason you don't/can't use something like WHERE username = '?'您的版本无效的原因正是您不/不能使用WHERE username = '?' but instead would use WHERE username = ?而是使用WHERE username = ? (no quotes around ? ). (周围没有引号? )。

If you want to add java list objects into a json array like mentioned below:如果要将 java 列表对象添加到如下所述的 json 数组中:

{"abc":["var1":"val1","var2":"val2","var3":"val3"]}

If there is already a json value in the column then you can use JSON_SET to update value.如果列中已经有一个 json 值,那么您可以使用 JSON_SET 来更新值。

            String query;
            query = "UPADTE tbl1 SET col1 = JSON_SET(col1, '$.abc', CAST(? AS JSON) ) WHERE cdtn = ?"; 
            // if col1 is null then, JSON_SET would be: JSON_SET('{}', '$.abc', CAST(? AS JSON) )
            try (Connection conn = DBUtil.getConnection();
                 PreparedStatement ps = conn.prepareStatement(query)) {
                ps.setString(1, jsonArray.toString());
                ps.setString(2, cd);
                ps.executeUpdate();
            }
            catch (SQLException e) {
                log.error("Error : ", e);
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM