java通过数据库连接池的方式连接数据库(C3P0)

来源: AwersomeSun 发布时间:2018-12-08 11:36:43 阅读量:844

数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个;释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏。这项技术能明显提高对数据库操作的性能。 


对于数据库连接池,我举一个小小的例子,通过这个例子(虽然不妥当)。我们可以吧数据库理解为一个大的池塘。;连接池为池塘里面的各个小的池塘(相当于一个容器),这个小的池塘里面,存储了我们岁要访问的数据库的相关信息。所以,当我们要访问数据库的时候,我们要访问这个容器,再从这个容器里卖弄取数据,因此,不产生对原数据库的直接操作,从而保护数据(个人理解,好懂就行)


我一般喜欢用C3P0。C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。即便喜欢用,但是对于通过配置C3P0来对数据库建立连接,我还是不太会,所以,我不采用这种配置的方法。


在百度百科里面,有关于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 创建时间 2018年5月13日

* @description 通过配置文件的形式,建立对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("已经连接成功");

 

}

 

}

上面的结果是这个:




似乎感觉还没有我直接用来的好。下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  利用数据库连接池对数据库进行连接

 * */

ComboPooledDataSource combo = new ComboPooledDataSource();

private MyDBManger() {

// TODO Auto-generated method stub

try {

combo.setDriverClass("com.mysql.jdbc.Driver"); // 加载驱动

combo.setPassword(""); 

combo.setUser("root");

combo.setJdbcUrl("jdbc:mysql:///auto_smart"); // 地址可以换成云端

combo.setMaxPoolSize(10); //池中最大的数量

combo.setMinPoolSize(3);

combo.setCheckoutTimeout(20000); // 超时连接,断

//测试下

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;

}

//外面调用获得数据库连接对象,调用此方法

public Connection getconnection() throws SQLException{

return combo.getConnection();

}

public static void main(String[] args) {

// TODO Auto-generated method stub

new MyDBManger();

}

 

}

就向上面的那样,我们调用这个程序,就可以直接得到一个数据库的连接。


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 相当于一辆货车,把数据库连接里取数据出来

rs = statement.executeQuery("SELECT * FROM autohome ");

System.out.println(

"编号" +"\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();

}

 

}

对于常用的数据库操作,无非增删查改,对于一些存储过程,触发器之类的,还是算了吧。


先看增,增无非就是insert 。


// 往数据库中插入数据

private void Insert() {

try {

// 得到一个数据库的连接

connection = DataBaseManger.getDBManger().getconnection();

statement = connection.createStatement();

// 做插入

statement.executeUpdate(sql);  // sql为sql语句

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

再看删,其实删和增,是一样的。包括改在内。也就是一个sql语句的不一样。其他的都一样的操作。


对于查,整的来说,也是一样的,唯一不同的是,他的返回值可以有好多,而对于增删改,返回值是int 类型:


int executeUpdate(String sql) throws SQLException;


下面的这个是查找的代码,因为做的是一个服务器,所以最后都是转化成json的格式发。不影响。


 try {

    connection = MyDBManger.getDBManger().getconnection();// 得到一个连接

    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();


具体的怎么实现这个增删查改,我就直接用网上的一些代码好了。别人写的也是挺好的代码,为啥不用呢?是吧。做个参考。


这个DBConnection.java类,其实就是一个数据库的开关,只是他没用数据库连接池。是直接连接的。


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);// 加载驱动程序

            conn = (Connection) DriverManager.getConnection(url, user, password);// 连续数据库

            

            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();//关闭连接 

        } catch (Exception e) {

            e.printStackTrace();

        }

        return i;//返回影响的行数,1为执行成功

    }

    //查找操作

    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");

                //可以将查找到的值写入类,然后返回相应的对象 

                //这里 先用输出的端口显示一下

                System.out.println(uname +"\t"+ uemail +"\t"+ uhiredate);

            }

            rs.close();

            db.close();//关闭连接 

        } 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();//关闭连接 

        } catch (SQLException e) {

            e.printStackTrace();

        }

        return i;//返回影响的行数,1为执行成功

    }

    //删除操作

    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();//关闭连接 

        } catch (SQLException e){

            e.printStackTrace();

        }

        return i;//返回影响的行数,1为执行成功

    }

}

 



标签: 数据库
分享:
评论:
你还没有登录,请先