如何将JSON文件导入MySQL数据库。如果我可以获得存储过程,或者将自动将所需文件推送到MySQL DB的java程序,那将是一件好事。
答案 0 :(得分:0)
假设你的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;
}