我需要将 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();
}
}
}
最佳答案
DB2 有一个名为“CLOB”的列类型,它与 SQL 文本类型相同(我认为)
你尝试过吗?
关于java - JSON:从数据库(DB2)插入和检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20574274/