如何使用JDBC在mysql中读取JSON数据类型 [英] How to read JSON data type in mysql using JDBC

查看:878
本文介绍了如何使用JDBC在mysql中读取JSON数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

由于没有兼容的结果集功能,因此我该如何使用以及使用什么来检索存储在此数据类型中的数据.

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

推荐答案

应该为rs.getString,因为getStringVARCHARTEXT一起使用,我们可以将JSon视为String类型,因此您可以使用getString获得结果.

It should be rs.getString, because getString used with VARCHAR, TEXT, we can consider JSon like a String type, so you can get the result, using getString.

简单示例

使用MySQL 5.7和PostgreSQL 9.4进行双重检查:

Double check with MySQL 5.7 and PostgreSQL 9.4 :

MySQL 5.7 SQL

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

代码

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();
    }
}

它会打印给我:

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

这篇关于如何使用JDBC在mysql中读取JSON数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆