【问题标题】:Import json file to mysql database using Java?使用Java将json文件导入mysql数据库?
【发布时间】:2017-12-19 05:57:15
【问题描述】:

如何将 JSON 文件导入 MySQL 数据库。如果我能获得一个存储过程,或者一个能够自动将所需文件推送到 MySQL DB 的 java 程序,那就太好了。

【问题讨论】:

标签: java mysql json


【解决方案1】:

假设您的 JSON 如下所示:

    {
           "employee": 
           {
              "id": "100",

              "name": "ABC",

              "address": "New York"
           }
    }

我们可以使用 JSON 解析器来解析 JSON。看看我的代码:

public int insertJSONtoDB() throws Exception {
    int status = 0;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "root");
        PreparedStatement preparedStatement = con.prepareStatement("insert into  employee values ( ?, ?, ? )");
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(new FileReader("c.\\employee.json")); 
        JSONObject jsonObject = (JSONObject) obj;

        String id = (String) jsonObject.get("id"); // from JSON tag
        preparedStatement.setString(1, id); // to the Database table

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

        String address = (String) itemize.get("address");
        preparedStatement.setString(3, address);

        status = preparedStatement.executeUpdate();

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

        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
    return status;
}

【讨论】:

    猜你喜欢
    • 2017-08-07
    • 1970-01-01
    • 2021-12-30
    • 2013-02-19
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    相关资源
    最近更新 更多