版权声明:觉得还行的话,右上角点个赞哟。 https://blog.csdn.net/u014384314/article/details/85217392
测试类:
package com.yw.dao;
import com.yw.entity.Student;
import com.yw.util.JDBCHelper;
import java.util.ArrayList;
import java.util.List;
public class mysqlOption {
public static void main(String args[]) {
List<Student> students = new ArrayList<Student>();
for (int i = 5; i < 60; i++) {
Student student = new Student();
student.setId(i);
student.setName("wangwu" + i);
student.setAge(23 + i);
students.add(student);
}
insert(students);
}
public static void insert( List<Student> students) {
// 获取一个jdbc实例(JDBCHelper是单例类)
JDBCHelper jdbcHelper = JDBCHelper.getInstance();
String sql = "insert into student values(?,?,?)";
jdbcHelper.executeBatch(sql, students);
}
}
1.定义一个单例类(采用静态内部类:线程安全、延迟加载、效率高)
package com.yw.util;
import com.yw.entity.Student;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
/**
* desc:单例类
*/
public class JDBCHelper {
// 设置单例
private JDBCHelper() {
}
private static class JDBCHelperInstance {
private static final JDBCHelper INSTANCE = new JDBCHelper();
}
public static JDBCHelper getInstance() {
return JDBCHelperInstance.INSTANCE;
}
// 数据库连接池
// private LinkedList<Collection> datasource = new LinkedList<Collection>();
// 建立数据库连接
static {
try {
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
private static Connection getConnect() {
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
String username = "root";
String password = "123456";
Connection con = null;
try {
con = DriverManager.getConnection(url, username, password);
} catch (SQLException se) {
System.out.println("数据库连接失败!");
se.printStackTrace();
}
return con;
}
// 批量执行
public void executeBatch(String sql, List<Student> students) {
Connection collection = null;
PreparedStatement pstmt = null;
int i = 0;
try {
// 使用自带连接
//collection = getConnect();
// 使用阿里巴巴连接池
collection = alibabaPool.getConn();
//启动事务---把自动提交设置为false
collection.setAutoCommit(false);
pstmt = collection.prepareStatement(sql);
// 将students 批量载入pstmt
if (students != null && students.size() > 0) {
for (Student student : students) {
pstmt.setObject(1, student.getId());
pstmt.setObject(2, student.getName());
pstmt.setObject(3, student.getAge());
//把这些操作添加到批处理中
pstmt.addBatch();
++i;
//每500条执行一次,避免内存不够的情况,可参考,Eclipse设置JVM的内存参数
if (i > 0 && i % 50 == 0) {
pstmt.executeBatch();
//如果不想出错后,完全没保留数据,则可以每执行一次提交一次,但得保证数据不会重复
collection.commit();
}
}
}
// 执行批操作(执行批量的sql语句)
//执行最后剩下不够500条的
pstmt.executeBatch();
// 批处理操作完成后,提交事务
collection.commit();
} catch (SQLException e) {
//回滚事务---把所有的操作都取消
try {
collection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
try {
//关闭事务---把自动提交事务设置为true
collection.setAutoCommit(true);
//关闭资源
// collection.close();
alibabaPool.close(pstmt,collection);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
实体类
package com.yw.entity;
import java.io.Serializable;
public class Student implements Serializable{
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yw</groupId>
<artifactId>curd2mysql</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
<!-- 阿里巴巴 druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
</dependencies>
</project>
使用阿里巴巴连接池
package com.yw.util;
import com.alibaba.druid.pool.DruidDataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class alibabaPool {
//声明druid连接池对象
private static DruidDataSource ds;
private static void loadProp() {
try {
Properties prop = new Properties();
InputStream is = alibabaPool.class.getResourceAsStream("/jdbc.properties");
System.out.println("sadasdasdasd");
prop.load(is);
String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
String maxActive = prop.getProperty("maxActive");
//声明DruidDataSource
ds = new DruidDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
ds.setMaxActive(Integer.parseInt(maxActive));
}catch (IOException e) {
e.printStackTrace();
}
}
/**
* 链接获取
*
* @return
*/
public static Connection getConn() {
try {
//如果连接池为空或者被异常关闭,则重新初始化一个
if (ds == null || ds.isClosed() ) {
loadProp();
}
return ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 资源关闭
*
* @param stmt
* @param conn
*/
public static void close(PreparedStatement stmt, Connection conn) {
try {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
配置文件
# 阿里巴巴连接池配置文件
#initialSize=10
#minIdle=10
#maxActive=50
#maxWait=60000
#timeBetweenEvictionRunsMillis=60000
#minEvictableIdleTimeMillis=300000
#validationQuery=SELECT 'x' FROM DUAL
#testWhileIdle=true
#testOnBorrow=false
#testOnReturn=false
#poolPreparedStatements=true
#maxPoolPreparedStatementPerConnectionSize=20
#filters=wall,stat
maxActive=50
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true
username=root
password=123456
driver=com.mysql.jdbc.Driver