數據庫連接池
-
概念
其實就是一個容器(集合),存放數據庫連接的容器。
當系統初始化好後,容器被創建,容器中會申請一些連接對象,當用戶來訪問數據庫時,從容器中獲取連接對象,用戶訪問完之後,會將連接對象歸還給容器。 -
好處
- 節約資源
- 用戶訪問高效
-
實現
- 標準接口:DataSource javax.sql包下的
方法:
獲取連接:getConnection()
歸還連接:Connection.close()。如果連接對象Connection是從連接池中獲取的,那麼調用Connection.close()方法,則不會再關閉連接了。而是歸還連接 - 一般我們不去實現它,有數據庫廠商來實現
- C3P0:數據庫連接池技術
- Druid:數據庫連接池實現技術,由阿里巴巴提供的
- 標準接口:DataSource javax.sql包下的
C3P0使用實例
步驟
1.導入jar包(兩個)這裏我是:c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar(數據庫驅動jar包也不要忘記)
2.定義配置文件
名稱:c3p0.properties 或者 c3p0-config.xml(這裏的配置文件名稱是規定的,不能自定義名字)
路徑:直接將文件放在src目錄下
Demo
package demo_jdbcpool;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class c3p0_demo {
public static void main(String[] args){
Connection conn = null;
PreparedStatement pst=null;
ResultSet rs =null;
try {
//新建數據庫連接池對象
DataSource ds=new ComboPooledDataSource();
conn = ds.getConnection();
//定義sql語句
String sql="SELECT * FROM account";
//創建sql執行對象
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("NAME");
double balance = rs.getDouble("balance");
System.out.println("id:"+id+"name:"+name+"balance"+balance);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
if(rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(pst!=null){
try {
pst.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
結果
Druid使用實例
步驟
1.導入jar包 這裏我是:druid-1.0.9.jar
2.定義配置文件
可以叫任意名稱的properties,可以放在任意目錄下
demo
package demo_jdbcpool;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class Druid_demo {
public static void main(String[] args){
Connection conn = null;
PreparedStatement pst=null;
ResultSet rs =null;
try {
Properties pro=new Properties();
pro.load(Druid_demo.class.getClassLoader().getResourceAsStream("druid.properties"));
//新建數據庫連接池對象
DataSource ds=DruidDataSourceFactory.createDataSource(pro);
conn = ds.getConnection();
//定義sql語句
String sql="SELECT * FROM account";
//創建sql執行對象
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("NAME");
double balance = rs.getDouble("balance");
System.out.println("id:"+id+"name:"+name+"balance"+balance);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(pst!=null){
try {
pst.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
結果
實現Drudi的JDBCUtils工具類
package demo_jdbcpool.Utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCUtils {
private static DataSource ds;
static{
try {
Properties pro=new Properties();
pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
ds= DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//獲取數據庫連接
public static Connection getconnection() throws SQLException {
return ds.getConnection();
}
//回收資源
public static void close(Statement st,Connection conn){
close(null,st,conn);
}
public static void close(ResultSet rs,Statement st,Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
//獲取連接池
public static DataSource getDataSource(){
return ds;
}
}
結合JDBCUtils工具類的Druid實例
package demo_jdbcpool;
import demo_jdbcpool.Utils.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Druid_demo {
public static void main(String[] args){
Connection conn = null;
PreparedStatement pst=null;
ResultSet rs =null;
try {
//新建數據庫連接池對象
conn = JDBCUtils.getconnection();
//定義sql語句
String sql="INSERT INTO account VALUES(null,?,?)";
//創建sql執行對象
pst = conn.prepareStatement(sql);
pst.setString(1,"wangwu");
pst.setDouble(2,3000);
int re = pst.executeUpdate();
System.out.println(re);
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtils.close(pst,conn);
}
}
}
結果
Spring JDBC
Spring框架對JDBC的簡單封裝。提供了一個JDBCTemplate對象簡化JDBC的開發
步驟
1.導入jar包
2.創建JdbcTemplate對象。依賴於數據源DataSource
JdbcTemplate template = new JdbcTemplate(ds);
3.調用JdbcTemplate的方法來完成CRUD的操作
update():執行DML語句。增、刪、改語句
queryForMap():查詢結果將結果集封裝爲map集合,將列名作爲key,將值作爲value 將這條記錄封裝爲一個map集合(**注意:這個方法查詢的結果集長度只能是1**)
queryForList():查詢結果將結果集封裝爲list集合(**注意:將每一條記錄封裝爲一個Map集合,再將Map集合裝載到List集合中**)
query():查詢結果,將結果封裝爲JavaBean對象
query的參數:RowMapper
一般我們使用BeanPropertyRowMapper實現類。可以完成數據到JavaBean的自動封裝
new BeanPropertyRowMapper<類型>(類型.class)
queryForObject:查詢結果,將結果封裝爲對象
(一般用於聚合函數的查詢)
練習Demo
package demo_jdbcpool;
import demo_jdbcpool.Utils.JDBCUtils;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
import java.util.Map;
public class template_demo {
//這裏利用JDBCUtils工具類,獲取datasource
//1. 修改1號數據的 salary 爲 10000
@Test
public void test1(){
JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
String sql="UPDATE emp SET salary=10000 WHERE id=?";
int re = template.update(sql, 1001);
System.out.println(re);
}
//2. 添加一條記錄
@Test
public void test2(){
JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
String sql="INSERT INTO emp(id,ename,job_id) VALUES(?,?,?)";
int re = template.update(sql, 1015, "張三", 4);
System.out.println(re);
}
//3. 刪除剛纔添加的記錄
@Test
public void test3(){
JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
String sql="DELETE FROM emp WHERE id=?";
int re = template.update(sql, 1015);
System.out.println(re);
}
//4. 查詢id爲1的記錄,將其封裝爲Map集合
@Test
public void test4(){
JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
String sql="SELECT * FROM emp WHERE id=?";
Map<String, Object> map = template.queryForMap(sql, 1001);
System.out.println(map);
}
//5. 查詢所有記錄,將其封裝爲List
@Test
public void test5(){
JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
String sql="SELECT * FROM emp";
List<Map<String, Object>> maps = template.queryForList(sql);
for (Map<String, Object> map : maps) {
System.out.println(map);
}
}
//6. 查詢所有記錄,將其封裝爲Emp對象的List集合
@Test
public void test6(){
JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
String sql="SELECT * FROM emp";
List<emp> query = template.query(sql, new BeanPropertyRowMapper<emp>(emp.class));
for (emp e : query) {
System.out.println(e);
}
}
//7. 查詢總記錄數
@Test
public void test7(){
JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
String sql="SELECT COUNT(id) FROM emp";
Integer re = template.queryForObject(sql, int.class);
System.out.println(re);
}
}