json数据存入mysql数据库中_将json数据存入数据库中
使用jar包:
mysql-connector-java-5.1.7-bin.jar
fastjson-1.2.53.jar
读取文件:
代码:
package degisn1;
import java.io.File;
import java.io.IOException;
import java.sql.DriverManager;
import org.apache.commons.io.FileUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.ssm.po.Word;
/**
* @ClassName: Test
* @description: 用于读取json数据,并将次数记录在数据库中。
* @author:
* @Date: Apr 15, 2019 4:12:34 PM
*/
public class Test {
public static JSONArray getJSONArray(String url) {
// input存放json内容
String input = null;
// 读取json文件
File myFile = new File(url);
try {
input = FileUtils.readFileToString(myFile, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
// 将数组json转换为JSON数组对象
JSONArray jsonArray = JSON.parseArray(input);
return jsonArray;
}
public static void main(String[] args) throws Exception {
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mvcAndMybatis?characterEncoding=utf-8";
String user = "root";
String password = "123456";
PreparedStatement psql;
try {
Class.forName(driver);
con = (Connection) DriverManager.getConnection(url, user, password);
if (!con.isClosed())
System.out.println("连接成功");
// 得到json数据
Word word = new Word();
JSONArray jsonArray = getJSONArray("H:/json1.json");
psql = (PreparedStatement) con.prepareStatement("insert into wordCount(word, times) values(?,?)");
for (Object obj : jsonArray) {
JSONObject jsonObject = (JSONObject) obj;
psql.setString(1, jsonObject.getString("word"));
psql.setInt(2, jsonObject.getInteger("times"));
psql.executeUpdate();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
con.close();
System.out.println("执行成功");
}
}
}
运行结果:
更多推荐
所有评论(0)