Java 如何将 JSON 文档解析为数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20449484/
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-08-13 02:01:18  来源:igfitidea点击:

How to parse a JSON document into a database

javamysqljsonparsing

提问by Milap

I have a JSON document with information on a product, and I want to parse the JSON document and put it into a database.

我有一个包含产品信息的 JSON 文档,我想解析 JSON 文档并将其放入数据库中。

An Example JSON document:

一个示例 JSON 文档:

{
"itemize": {
   "pr": "2583",

       "n": "Chocolate donut",

       "yst": "A beautiful, premium chocolate donut"

       "wh": 2.99

}

Here is the code I have so far:

这是我到目前为止的代码:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class q1 {
public static void addProduct()
{
    JSONParser parser=new JSONParser();

    try{

        Object obj = parser.parse(new FileReader("c.\itemize.json"));
        JSONObject jsonObject = (JSONObject) obj;

        String pr = (String) jsonObject.get("Pr");
        //Put pr into database

        String n = (String) jsonObject.get("n");
        //Put n into database

        String yst = (String) jsonObject.get("yst");
        //Put yst into database

        String wh = (String) jsonObject.get("wh");
        //Put wh into database

    }
}
}

The database is in MySQL and has all these columns already. I just need to replace the commented lines in the java code with lines that will put the string into the database. This is what the database looks like:

数据库在 MySQL 中,并且已经拥有所有这些列。我只需要用将字符串放入数据库的行替换 java 代码中的注释行。这是数据库的样子:

Pr VARCHAR(30) NOT NULL,
n VARCHAR(30) NOT NULL,
yst VARCHAR(30) NOT NULL,
wh VARCHAR(30) NOT NULL,
Primary Key (Product_ID));

采纳答案by Shamse Alam

Java interface for accessing databases is Java Database Connectivity (JDBC). Using JDBC you can create a connection to the database, issue database queries and updates and receive the results. try the following code

用于访问数据库的 Java 接口是 Java 数据库连接 (JDBC)。使用 JDBC,您可以创建到数据库的连接、发出数据库查询和更新并接收结果。试试下面的代码

  private Connection connect = null;
  PreparedStatement preparedStatement = null;

 public int save() throws Exception {
   int status = 0;  
    try {
      // Load the MySQL driver, each DB has its own driver
      Class.forName("com.mysql.jdbc.Driver");

      // DB connection setup 
      connect = DriverManager.getConnection("jdbc:mysql://dbhost/database?" + "user=sqluser&password=sqluserpw");

      // PreparedStatements 
      preparedStatement = connect
          .prepareStatement("insert into  Table_Name values (?, ?, ?, ? )");

      Object obj = parser.parse(new FileReader("c.\itemize.json"));
      JSONObject jsonObject = (JSONObject) obj;

      String pr = (String) jsonObject.get("Pr");
      // Parameters start with 1
      preparedStatement.setString(1, pr);

      String n = (String) itemize.get("n");
      preparedStatement.setString(2, n);

      String yst = (String) jsonObject.get("yst");
      preparedStatement.setString(3, yst);

      String wh = (String) itemize.get("wh");
      preparedStatement.setString(4, wh);

      status = preparedStatement.executeUpdate();

    } catch (Exception e) {
      throw e;
    } finally {
      try {
          if (connect != null) {
             connect.close();
           }

         } catch (Exception e) {

         }
    }
    return status;
  }

回答by Prabhakaran Ramaswamy

Do like this.

这样做。

    Object obj = parser.parse(new FileReader("c.\itemize.json"));
    JSONObject jsonObject = (JSONObject ) obj;
    JSONObject   itemize = (JSONObject) jsonObject.get("itemize");
    String pr = (String) itemize.get("Pr");
    String n = (String) itemize.get("n");
    String yst = (String) itemize.get("yst");
    String wh = (String) itemize.get("wh");

回答by Sasi Kathimanda

First of all I recommend you to use qualified names for your variables both in your code and database. after all your code, use these lines to create inserts

首先,我建议您在代码和数据库中为变量使用限定名称。在所有代码之后,使用这些行来创建插入

  //use DriverManager to getConnection for your mySQL
    conObj = getConnection();
    String preQueryStatement = "INSERT  INTO  <TABLENAME>  VALUES  (?,?,?,?)";
    pStmnt = conObj.prepareStatement(preQueryStatement);
    pStmnt.setString(1, Pr );
    pStmnt.setString(2, n);
    pStmnt.setString(3, yst );
    pStmnt.setInt(4, wh );
 // execute insert SQL stetement
    preparedStatement .executeUpdate();