- public class Main {
- public static void main(String[] args) throws Exception{
- String sql = "insert into mobile_place(number,place) values(?,?)";
- int count = 0;//计数器
- Connection conn = JDBCUtil.getConnection();
- PreparedStatement pstmt = conn.prepareStatement(sql);
- try {
- InputStreamReader is = new InputStreamReader(new FileInputStream(new File("D:/CC.txt")),"utf-8");
- BufferedReader br = new BufferedReader(is);
- while(br.readLine() != null){
- conn.setAutoCommit(false);//设置数据手动提交,自己管理事务
- count++;//没读取一行数据,计数器+1
- String str = br.readLine().toString().trim();//读取一行数据
- String s1 = str.substring(0, str.indexOf(","));//取逗号以前的一段
- String s2 = str.substring(str.indexOf(",")+1,str.length());//取逗号之后的一段
- pstmt.setString(1, s1);
- pstmt.setString(2, s2);
- pstmt.addBatch();//用PreparedStatement的批量处理
- if(count%500==0){//当增加了500个批处理的时候再提交
- pstmt.executeBatch();//执行批处理
- conn.commit();//提交
- conn.close();//关闭数据库
- conn = JDBCUtil.getConnection();//重新获取一次连接
- conn.setAutoCommit(false);
- pstmt = conn.prepareStatement(sql);
- }
- System.out.println("已插入"+count+"条数据");
- }
- if(count%500!=0){//while循环外的判断,为了防止上面判断后剩下最后少于500条的数据没有被插入到数据库
- pstmt.executeBatch();
- conn.commit();
- }
- pstmt.close();
- conn.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- 500可以自己增大,执行效率很高。比单挑执行再插入快多了
- getConnection()为获取数据库连接
- public static Connection getConnection(){
- try {
- Class.forName("com.mysql.jdbc.Driver");
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- try {
- conn = DriverManager.getConnection(url, userName, password);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return conn;
- }
java jdbc向数据库插入大量数据
最新推荐文章于 2024-05-15 00:11:03 发布