事务
(一)事务的概念
(二)MySQL的事务操作
(三)JDBC事务的操作
操作:
1、开启事务 conn.setAutoCommit(false);
2、提交事务 conn.commit();
3、回滚事务 conn.rollback();
(四)事务的隔离级别(了解)
二、数据库连接池
(一)连接池简介
(二)手动实现连接池
代码
import com.wwz.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
//模拟数据库连接池
public class MyDataBasePool {
private MyDataBasePool(){}
//初始化连接数量
private static int conn_size = 10;
//定义一个集合作为连接池
private static List<Connection> connPools = new ArrayList<>();
//初始化连接池
static {
for (int i = 0; i < conn_size; i++) {
Connection connection = JdbcUtils.getConnection();
connPools.add(connection);
}
System.out.println("连接池初始化成功,创建连接数目为:"+conn_size);
}
//从连接池中获取连接
public static Connection getConnFromPools(){
Connection conn = connPools.get(0);
//从池中获得连接后,数据库连接池会相应减少该连接
connPools.remove(conn);
System.out.println("用户正在使用"+conn+"连接,当前连接池中剩余连接数目为:"+connPools.size());
return conn;
}
//用完归还连接
public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
try {
if (resultSet != null){
resultSet.close();
}
if (preparedStatement != null){
preparedStatement.close();
}
if (connection != null){
connPools.add(connection);
System.out.println("用户归还连接"+connection+"后,当前池子中剩余连接数目为:"+connPools.size());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestConnPools {
@Test
public void testPools(){
Connection connFromPools = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//从连接池获取连接
connFromPools = MyDataBasePool.getConnFromPools();
preparedStatement = connFromPools.prepareStatement("select * from account");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
int i = resultSet.getInt(1);
String s = resultSet.getString(2);
System.out.println(i+"\t"+s);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
//归还连接
MyDataBasePool.close(connFromPools,preparedStatement,resultSet);
}
}
}
(三)DBCP连接池
代码
(四)c3p0连接池
代码
三、DBUtils工具
(一)DBUtils工具简介
(二)JavaBean
(三)准备工作
(三)DBUtils之DML操作
(四)DBUtils之DQL操作