java 如何使用JDBC读取mysql中的JSON数据类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43283689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:17:15  来源:igfitidea点击:

How to read JSON data type in mysql using JDBC

javajdbc

提问by Kushan

Mysql 5.7 introduced the JSON data type which offers tonnes of query functions.

Mysql 5.7 引入了 JSON 数据类型,它提供了大量的查询功能。

Since there isn't a compatible resultset function, how and what to i do use retrieve the data stored in this datatype.

由于没有兼容的结果集函数,我如何以及如何使用检索存储在此数据类型中的数据。

采纳答案by YCF_L

It should be rs.getString, because getStringused with VARCHAR, TEXT, we can consider JSonlike a Stringtype, so you can get the result, using getString.

应该是rs.getString,因为getStringVARCHAR, 一起使用TEXT,我们可以认为JSon是一个String类型,所以可以得到结果,使用getString.



Simple Example

简单示例

Double check with MySQL 5.7 and PostgreSQL 9.4 :

仔细检查 MySQL 5.7 和 PostgreSQL 9.4 :

MySQL 5.7 SQL

MySQL 5.7 SQL

create database db_test;
create table table_test(json JSON);
INSERT INTO table_test VALUES('{"key1": "value1", "key2": "value2"}');

CODE

代码

public static void checkJSon() {
    try {
        Class.forName(DRIVER);
        Connection connection = DriverManager.getConnection(DB_URL, DB_username, DB_password);
        String q = "SELECT * FROM table_test";
        PreparedStatement preparedStatement = connection.prepareStatement(q);
        preparedStatement.execute();
        ResultSet rs = preparedStatement.executeQuery();
        while (rs.next()) {
            System.out.println(rs.getString("json"));
        }

    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    }
}

It print to me :

它打印给我:

{"key1": "value1", "key2": "value2"}