曾梦垚

导航

Java使用Mysql数据库实现批量添加数据

EmployeeDao.java

//批处理添加数据
public int saveEmploeeBatch(){
int row = 0;
try{
con = DBCon.getConn();
String sql = "insert into tb_employee(name,age,sex,duty)values(?,?,?,?)";
pstmt = (PreparedStatement) con.prepareStatement(sql);
Random random = new Random();
for(int i = 0; i < 10; i++){
pstmt.setString(1 , "22"+i);
pstmt.setInt(2, 1+i);
pstmt.setString(3, i % 2 == 0?"男":"女");
pstmt.setInt(4, random.nextInt(5)+10);
pstmt.addBatch();
}
int[] rows = pstmt.executeBatch();
row = rows.length;
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(pstmt != null)
pstmt.close();
}catch(Exception e){
e.printStackTrace();
}
try{
if(con != null)
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
return row;
}
 
TestSql05.java
package com.sql.test;
 
import com.sql.dao.EmployeeDao;
 
public class TestSql05 {
 
public static void main(String[] args){
int rows = EmployeeDao.getInstance().saveEmploeeBatch();
System.out.println("批量添加信息的行数是:"+rows);
}
}

posted on 2016-12-28 23:34  曾梦垚  阅读(9835)  评论(0编辑  收藏  举报