package com.input;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class AreaDao extends BaseDao {
/**
* 批量添加数据
*/
public void add(List<Object> list) throws Exception{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
int listSize = list.size();
Object object[] = null;
con = getCon();
con.setAutoCommit(false);//关闭事务自动提交
String sql = "INSERT INTO f_area(administrative_code, parent_administrative_code, grade, area_name, create_time) VALUES(?,?,?,?,?)";
ps = con.prepareStatement(sql);
System.out.println("---------总记录数为:"+list.size()+"-------------");
for(int i = 0;i < listSize;i++){
object = (Object[])list.get(i);
ps.setObject(1, object[0]);
ps.setObject(2, object[1]);
ps.setObject(3, object[2]);
ps.setObject(4, object[3]);
ps.setObject(5, sdf.format(date));
ps.addBatch(); //把一个SQL命令加入命令列表
if(i != 0 && i % 10 == 0){
System.out.println("=====执行了"+i+"条记录=====");
}
if(i == listSize - 1 ){
System.out.println("=====总共成功执行了"+listSize+"条记录=====");
}
}
ps.executeBatch();//执行批量更新
con.commit();//语句执行完毕,提交本事务
closeAll(rs, ps, con);
}
}
package com.input;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BaseDao {
private static final String url = "jdbc:mysql://127.0.0.1:3306/china_dress?zeroDateTimeBehavior=convertToNull&characterEncoding=utf-8";
private static final String username = "root";
private static final String password = "123456";
public Connection con = null;
public PreparedStatement ps = null;
public ResultSet rs = null;
/**
* 使用JDBC连接数据库
*/
public Connection getCon(){
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
/**
* 关闭连接
*/
public void closeAll(ResultSet rs, PreparedStatement ps, Connection con){
try {
if(rs != null){
rs.close();
}if(ps != null){
ps.close();
}if(con != null){
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 测试连接
*/
public static void main(String[] args) {
BaseDao baseDao = new BaseDao();
Connection conn = baseDao.getCon();
System.out.println("con:" + conn);
}
}
java 批量添加数据
最新推荐文章于 2024-07-22 16:19:47 发布