JSON:从数据库插入和检索(DB2)

时间:2013-12-13 19:16:42

标签: java json jackson

我需要将JSON字符串插入数据库(DB2)。我不认为我可以在这里使用VARCHAR数据类型,因为DB2中的列的最大限制是32,672。我希望在此列中插入的JSON可能包含更多字符。所以,我认为blob是一种数据类型。我能够成功插入。但是在检索时,我无法将blob对象强制转换为原始JSON。任何帮助将不胜感激。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class DerbyBlobDemo
{
private static String url      = "jdbc:derby://localhost:1527/test";
private static String username = "APP";
private static String password = "APP";

public static void main(String[] args) throws Exception
{
    insert();

    read();
}

static void insert() throws Exception
{
    Connection conn = null;
    FileInputStream fis = null;
    try
    {
        Class.forName("org.apache.derby.jdbc.ClientDriver");
        conn = DriverManager.getConnection(url, username, password);
        conn.setAutoCommit(false);


        String jsonSql = "INSERT INTO SCHEMA.TABLE "
            + "(ID, JSON) " + "VALUES (?, ?)";

        PreparedStatement stmt = conn.prepareStatement(jsonSql);

        stmt.setString(1, "014");

        File jsonFile = new File("path to my json");
        fis = new FileInputStream(jsonFile);
        stmt.setBinaryStream(2, fis);

        stmt.execute();

        conn.commit();
    }
    catch (SQLException e)
    {
        e.printStackTrace();
    }
    catch (FileNotFoundException fex)
    {
        fex.printStackTrace();
    }
    finally
    {
        if (fis != null)
        {
            fis.close();
        }
        if (conn != null
            && !conn.isClosed())
        {
            conn.close();
        }
    }
}

static void read() throws Exception
{
    Connection conn = null;
    try
    {
        Class.forName("org.apache.derby.jdbc.ClientDriver");
        conn = DriverManager.getConnection(url, username, password);
        conn.setAutoCommit(false);

        Statement select = conn.createStatement();
        ResultSet result = select.executeQuery("Select * from SCHEMA.TABLE");
        while (result.next())
        {
            String identifier = result.getString("ID");

            String json = result.getBlob("JSON").toString();

            JSONObject jsonresult = (JSONObject) new JSONParser().parse(json);

            // JSONArray arrayObj = JSONArray.fromObject(result.getBlob("JSON"));

            // JSONArray arrayObj = new JSONArray();
            System.out.println(jsonresult);
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
}

2 个答案:

答案 0 :(得分:1)

DB2有一个名为“CLOB”的列类型,它与SQL Text类型相同(我认为)

http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=%2Fcom.ibm.db2z10.doc.intro%2Fsrc%2Ftpc%2Fdb2z_largeobjectdatatypes.htm

你试过吗?

答案 1 :(得分:0)

Blob接口未声明 toString()的任何合约,因此可能会根据Object implementation返回值。毕竟,没有标准的方法将任意字节序列转换为UTF-16 String

所以,这条线不起作用:

String json = result.getBlob("JSON").toString();

你正在使用JSON.simple而不是杰克逊在问题中被标记(我不知道为什么你需要两者。)

假设文件编码为UTF-8,您可以使用以下方法解析数据:

static Object parseJson(Blob blob) throws SQLException, IOException,
    ParseException {
  try (InputStream in = blob.getBinaryStream();
      Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) {
    return new JSONParser().parse(reader);
  }
}

如果您需要防止JSON文件是其他Unicode编码的可能性,则会详细描述检测方法here