jdbc 批量操作 batch

PreparedStatement的预编译空间有限,数据量特别的大,所以 

大量的数据处理的时候就需要使用Statement了

package com.testJDBC;

import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Driver;

public class TestBatch {
	public static void main(String[] args) {
		Connection conn = null;
			Statement sm = null; // 此处的Statement 是接口 不是实现类;
		
			try {
				// 加载类资源
				Class.forName("com.mysql.jdbc.Driver");
				// 这个的Connection 会连接时间很长,所以的话,后面会使用线程池进行管理
				 conn = (Connection) DriverManager.getConnection(
						"jdbc:mysql://localhost:3306/testjdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false",
						"root",
						"wangrong654688");
				 
				 conn.setAutoCommit(false);
				 
				 sm = conn.createStatement();
				 
				for(int i=0;i<100;i++) { // 批量操作
					sm.addBatch("insert into t_user(username,pwd,resTime) value('leon"+i+"',123456,now())");
				}
				sm.executeBatch();
				
				 conn.commit();  // 最后一次提交
				System.out.println("成功");
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}catch (SQLException e) {
				e.printStackTrace();
				// TODO: handle exception
			}finally { // 关闭原则 先进后关
				
				try {
					if(sm!=null) {
					sm.close();
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
				try {
					if(conn!=null) {
					conn.close();
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}	
	}

}
发布了189 篇原创文章 · 获赞 10 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/wangrong111222/article/details/104081009