jdbc批量插入实例

2021-12-23 11:26:54 浏览数 (1)

代码语言:javascript复制
package test;

import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;

import com.allinfinance.cis.br.infrastructure.TmBrIvsOut;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;


public class testIvs {
	public static void main(String args[]){
		TmBrIvsOut tmBrIvsOut=new TmBrIvsOut();
		tmBrIvsOut.setOutId(3);
		tmBrIvsOut.setOrg("001");
		tmBrIvsOut.setCustId("22");
		TmBrIvsOut tmBrIvsOut2=new TmBrIvsOut();
		tmBrIvsOut2.setOutId(4);
		tmBrIvsOut2.setOrg("001");
		tmBrIvsOut2.setCustId("22");
		List<TmBrIvsOut> tmBrIvsOuts=new ArrayList<TmBrIvsOut>();
		tmBrIvsOuts.add(tmBrIvsOut2);
		tmBrIvsOuts.add(tmBrIvsOut);
		//以一次性插入上面两条数据为例
		try {
			batchInsert(tmBrIvsOuts);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void batchInsert(List<TmBrIvsOut> tmBrIvsOuts) throws Exception {
		Class.forName("com.mysql.jdbc.Driver");//获取驱动
		Connection conn=(Connection) DriverManager.getConnection("jdbc:mysql://10.2.17.37:3306/cis?useServerPrepStmts=false&rewriteBatchedStatements=true",
                       "username", "password");//连接数据库
		conn.setAutoCommit(false);//关闭自动提交
		PreparedStatement ps=(PreparedStatement) conn.prepareStatement("insert into TM_BR_IVS_OUT "
				 "(org,cust_id,out_id,code_key,code_value,out_name)"  "values"  "(?,?,?,?,?,?)");//sql语句
		for(TmBrIvsOut tb:tmBrIvsOuts){
			//1,2,3....表示sql中对应的每个?
			ps.setString(1, tb.getOrg());
			ps.setString(2, tb.getCustId());
			ps.setLong(3, tb.getOutId());
			ps.setString(4, null);
			ps.setString(5, null);
			ps.setString(6, null);
			ps.addBatch();//手机多条数据
		}
		ps.executeBatch();//同时提交多条数据
		conn.commit();
		ps.close();
		ps.close();
		System.out.println("success");
	}

}

0 人点赞