來源: AwersomeSun 發(fā)布時(shí)間:2018-12-08 11:36:43 閱讀量:982
數(shù)據(jù)庫連接池負(fù)責(zé)分配、管理和釋放數(shù)據(jù)庫連接,它允許應(yīng)用程序重復(fù)使用一個(gè)現(xiàn)有的數(shù)據(jù)庫連接,而不是再重新建立一個(gè);釋放空閑時(shí)間超過最大空閑時(shí)間的數(shù)據(jù)庫連接來避免因?yàn)闆]有釋放數(shù)據(jù)庫連接而引起的數(shù)據(jù)庫連接遺漏。這項(xiàng)技術(shù)能明顯提高對(duì)數(shù)據(jù)庫操作的性能。
對(duì)于數(shù)據(jù)庫連接池,我舉一個(gè)小小的例子,通過這個(gè)例子(雖然不妥當(dāng))。我們可以吧數(shù)據(jù)庫理解為一個(gè)大的池塘。;連接池為池塘里面的各個(gè)小的池塘(相當(dāng)于一個(gè)容器),這個(gè)小的池塘里面,存儲(chǔ)了我們歲要訪問的數(shù)據(jù)庫的相關(guān)信息。所以,當(dāng)我們要訪問數(shù)據(jù)庫的時(shí)候,我們要訪問這個(gè)容器,再從這個(gè)容器里賣弄取數(shù)據(jù),因此,不產(chǎn)生對(duì)原數(shù)據(jù)庫的直接操作,從而保護(hù)數(shù)據(jù)(個(gè)人理解,好懂就行)
我一般喜歡用C3P0。C3P0是一個(gè)開源的JDBC連接池,它實(shí)現(xiàn)了數(shù)據(jù)源和JNDI綁定,支持JDBC3規(guī)范和JDBC2的標(biāo)準(zhǔn)擴(kuò)展。即便喜歡用,但是對(duì)于通過配置C3P0來對(duì)數(shù)據(jù)庫建立連接,我還是不太會(huì),所以,我不采用這種配置的方法。
在百度百科里面,有關(guān)于C3P0的具體配置,可以直接使用
config.properties配置文件
DriverClass = com.mysql.jdbc.Driver
JdbcUrl = jdbc:mysql://IP:3306/auto_smart_home_data?useUnicode=true&characterEncoding=UTF-8
User = root
Password = 123
MaxPoolSize = 20
MinPoolSize = 2
InitialPoolSize = 5
MaxStatements = 30
MaxIdleTime =100
接下來,便是java使用了:
package com.MySql;
import java.sql.Connection;
import java.util.Properties;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/*
* @author 22923
* @date 創(chuàng)建時(shí)間 2018年5月13日
* @description 通過配置文件的形式,建立對(duì)C3P0的操作,
*/
public class C3P0Mysql {
private ComboPooledDataSource cpds;
private static C3P0Mysql c3P0Properties;
static{
c3P0Properties = new C3P0Mysql();
}
public C3P0Mysql() {
try {
cpds = new ComboPooledDataSource();
//加載配置文件
Properties props = new Properties();
props.load(C3P0Mysql.class.getClassLoader().getResourceAsStream("config.properties"));
cpds.setDriverClass(props.getProperty("DriverClass"));
cpds.setJdbcUrl(props.getProperty("JdbcUrl"));
cpds.setUser(props.getProperty("User"));
cpds.setPassword(props.getProperty("Password"));
cpds.setMaxPoolSize(Integer.parseInt(props.getProperty("MaxPoolSize")));
cpds.setMinPoolSize(Integer.parseInt(props.getProperty("MinPoolSize")));
cpds.setInitialPoolSize(Integer.parseInt(props.getProperty("InitialPoolSize")));
cpds.setMaxStatements(Integer.parseInt(props.getProperty("MaxStatements")));
cpds.setMaxIdleTime(Integer.parseInt(props.getProperty("MaxIdleTime")));
} catch (Exception e) {
e.printStackTrace();
}
}
public static C3P0Mysql getInstance(){
return c3P0Properties;
}
public Connection getConnection(){
Connection conn = null;
try {
conn = cpds.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection connection = C3P0Mysql.c3P0Properties.getConnection();
System.out.println("已經(jīng)連接成功");
}
}
上面的結(jié)果是這個(gè):
似乎感覺還沒有我直接用來的好。下main是我直接在java中建立連接。
package com.MySql;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class MyDBManger {
/**
* @author sunyang_ah@163.com
* @return
* @function 利用數(shù)據(jù)庫連接池對(duì)數(shù)據(jù)庫進(jìn)行連接
* */
ComboPooledDataSource combo = new ComboPooledDataSource();
private MyDBManger() {
// TODO Auto-generated method stub
try {
combo.setDriverClass("com.mysql.jdbc.Driver"); // 加載驅(qū)動(dòng)
combo.setPassword("");
combo.setUser("root");
combo.setJdbcUrl("jdbc:mysql:///auto_smart"); // 地址可以換成云端
combo.setMaxPoolSize(10); //池中最大的數(shù)量
combo.setMinPoolSize(3);
combo.setCheckoutTimeout(20000); // 超時(shí)連接,斷
//測試下
combo.getConnection().close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("error : "+ e.getMessage());
}
}
private static MyDBManger DBManager = new MyDBManger();
public static MyDBManger getDBManger(){
return DBManager;
}
//外面調(diào)用獲得數(shù)據(jù)庫連接對(duì)象,調(diào)用此方法
public Connection getconnection() throws SQLException{
return combo.getConnection();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new MyDBManger();
}
}
就向上面的那樣,我們調(diào)用這個(gè)程序,就可以直接得到一個(gè)數(shù)據(jù)庫的連接。
package com.MySql;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
public class DemoTest {
Connection connection = null ;
ResultSet rs = null ;
Statement statement = null ;
public DemoTest() {
// TODO Auto-generated constructor stub
try {
connection = MyDBManger.getDBManger().getconnection();
statement = connection.createStatement();// statement 相當(dāng)于一輛貨車,把數(shù)據(jù)庫連接里取數(shù)據(jù)出來
rs = statement.executeQuery("SELECT * FROM autohome ");
System.out.println(
"編號(hào)" +"\t"+ "名字" +"\t"+"密碼" +"\t"
);
while(rs.next()) {
System.out.println(
rs.getString("ID") +"\t"+
rs.getString("DATETIME") +"\t"+
rs.getString("TEMPTURE") +"\t"
);
}
connection.close();
rs.close();
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new DemoTest();
}
}
對(duì)于常用的數(shù)據(jù)庫操作,無非增刪查改,對(duì)于一些存儲(chǔ)過程,觸發(fā)器之類的,還是算了吧。
先看增,增無非就是insert 。
// 往數(shù)據(jù)庫中插入數(shù)據(jù)
private void Insert() {
try {
// 得到一個(gè)數(shù)據(jù)庫的連接
connection = DataBaseManger.getDBManger().getconnection();
statement = connection.createStatement();
// 做插入
statement.executeUpdate(sql); // sql為sql語句
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
再看刪,其實(shí)刪和增,是一樣的。包括改在內(nèi)。也就是一個(gè)sql語句的不一樣。其他的都一樣的操作。
對(duì)于查,整的來說,也是一樣的,唯一不同的是,他的返回值可以有好多,而對(duì)于增刪改,返回值是int 類型:
int executeUpdate(String sql) throws SQLException;
下面的這個(gè)是查找的代碼,因?yàn)樽龅氖且粋€(gè)服務(wù)器,所以最后都是轉(zhuǎn)化成json的格式發(fā)。不影響。
try {
connection = MyDBManger.getDBManger().getconnection();// 得到一個(gè)連接
st = connection.createStatement();
rs = st.executeQuery("select id,temperature,humidity,co,createTime from checkdata order by id desc LIMIT 1");
System.out.println("====================================");
while(rs.next()){
try {
json.put("id", rs.getInt("id"));
json.put("temp", rs.getDouble("temperature"));
json.put("hum", rs.getDouble("humidity"));
json.put("co", rs.getDouble("co"));
json.put("time", rs.getString("createTime"));
out.write(json.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(json.toString());
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
具體的怎么實(shí)現(xiàn)這個(gè)增刪查改,我就直接用網(wǎng)上的一些代碼好了。別人寫的也是挺好的代碼,為啥不用呢?是吧。做個(gè)參考。
這個(gè)DBConnection.java類,其實(shí)就是一個(gè)數(shù)據(jù)庫的開關(guān),只是他沒用數(shù)據(jù)庫連接池。是直接連接的。
public class DBConnection {
String driver = "com.mysql.jdbc.Driver";
String url= "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
public Connection conn;
public DBConnection() {
try {
Class.forName(driver);// 加載驅(qū)動(dòng)程序
conn = (Connection) DriverManager.getConnection(url, user, password);// 連續(xù)數(shù)據(jù)庫
if(!conn.isClosed())
System.out.println("Succeeded connecting to the Database!");
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
this.conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class JDBCTest {
public static void main(String[] args){
//add(uname, uemail, upwd);
//update("李詩詩","lishishi@com","666");
//show();
del("王小五");
}
//插入操作
public static int add(String uname,String uemail,String upwd) {
int i=0;
String sql="insert into employee (name,email,pwd) values (?,?,?)";
DBConnection db = new DBConnection();
try {
PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(sql);
preStmt.setString(1, uname);
preStmt.setString(2, uemail);
preStmt.setString(3, upwd);
preStmt.executeUpdate();
//Statement statement = (Statement) db.conn.createStatement();
//statement.executeUpdate(sql);
preStmt.close();
db.close();//關(guān)閉連接
} catch (Exception e) {
e.printStackTrace();
}
return i;//返回影響的行數(shù),1為執(zhí)行成功
}
//查找操作
public static void show(){
String sql ="select * from employee";
DBConnection db = new DBConnection();
System.out.println("-----------------");
System.out.println("姓名" +"\t"+ "郵箱" +"\t"+ "日期");
System.out.println("-----------------");
try {
Statement stmt = (Statement) db.conn.createStatement();
ResultSet rs = (ResultSet) stmt.executeQuery(sql);
while(rs.next()){
String uname = rs.getString("name");
String uemail = rs.getString("email");
String uhiredate = rs.getString("hiredate");
//可以將查找到的值寫入類,然后返回相應(yīng)的對(duì)象
//這里 先用輸出的端口顯示一下
System.out.println(uname +"\t"+ uemail +"\t"+ uhiredate);
}
rs.close();
db.close();//關(guān)閉連接
} catch (SQLException e) {
e.printStackTrace();
}
}
//更新操作
public static int update(String uname,String uemail,String upwd) {
int i =0;
String sql="update employee set email=?,pwd=? where name=?";
DBConnection db = new DBConnection();
try {
PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(sql);
preStmt.setString(1, uemail);
preStmt.setString(2, upwd);
preStmt.setString(3, uname);
preStmt.executeUpdate();
preStmt.close();
db.close();//關(guān)閉連接
} catch (SQLException e) {
e.printStackTrace();
}
return i;//返回影響的行數(shù),1為執(zhí)行成功
}
//刪除操作
public static int del(String uname) {
int i=0;
String sql="delete from employee where name=?";
DBConnection db = new DBConnection();
try {
PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(sql);
preStmt.setString(1, uname);
preStmt.executeUpdate();
preStmt.close();
db.close();//關(guān)閉連接
} catch (SQLException e){
e.printStackTrace();
}
return i;//返回影響的行數(shù),1為執(zhí)行成功
}
}