package com.swift; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import ja... ...
package com.swift; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import com.google.gson.Gson; public class AddAll { /** * 將D盤D:\java_JDK\java_date路徑下的jzkt.json文件中的json駕照考試代碼用Gson解析成root對象 */ public static void main(String[] args) { File file = new File("D:\\java_JDK\\java_date", "jzkt.json"); StringBuilder sb = null; List<Result> list = null; try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8")); String str = null; sb = new StringBuilder(); final String LINE_SEPARATOR = System.getProperty("line.separator"); try { while ((str = br.readLine()) != null) { sb.append(str); sb.append(LINE_SEPARATOR); } Gson gson = new Gson(); Root root = gson.fromJson(sb.toString(), Root.class); list = root.getResult();//得到Result類型的對象列表集合 } catch (IOException e) { e.printStackTrace(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } if (addAll(list)) { System.out.println("添加成功"); } else { System.out.println("添加失敗"); } } private static boolean addAll(List<Result> list) { Connection conn = JDBCUtil.getConn(); PreparedStatement ps = null; try { ps = conn.prepareStatement("insert into sw_question values(?,?,?,?,?,?,?,?,?)"); for (int i = 0; i < list.size(); i++) {//不要用foreach的方法,查詢可以修改不行 System.out.println("i=" + i); ps.setInt(1, list.get(i).getId()); ps.setString(2, list.get(i).getQuestion()); ps.setString(3, list.get(i).getAnswer()); ps.setString(4, list.get(i).getItem1()); ps.setString(5, list.get(i).getItem2()); ps.setString(6, list.get(i).getItem3()); ps.setString(7, list.get(i).getItem4()); ps.setString(8, list.get(i).getExpalins()); ps.setString(9, list.get(i).getUrl()); ps.addBatch();//添加到批處理 ,使用ps.executeUpdate()永遠只能悲催的加一條數據 } ps.executeBatch();//執行批處理 return true; } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtil.closeAll(conn, ps, null); } return false; } }