package com.pax.pms.database;
import com.pax.pms.util.Log;
import org.apache.commons.dbcp2.BasicDataSource;
import javax.sql.DataSource;
import java.sql.*;
public class DbManager {
private final static String DRIVER = "com.mysql.jdbc.Driver";
// /*
private final static String URL = "jdbc:mysql://localhost:3306/sonar";
private final static String USERNAME = "sonar";
private final static String PASSWORD = "sonar";
// */
/*
private final static String URL = "jdbc:mysql://localhost:3306/pms";
private final static String USERNAME = "root";
private final static String PASSWORD = "root";
*/
private static DbManager dbManager;
public static DbManager getInstance() {
if (dbManager == null) {
dbManager = new DbManager();
}
//第一次要创建表
return dbManager;
}
private static BasicDataSource basicDS=null;
static{
basicDS=init();
}
public static BasicDataSource init(){
BasicDataSource tempDS=new BasicDataSource();
tempDS.setDriverClassName(DRIVER);
tempDS.setUrl(URL);
tempDS.setUsername(USERNAME);
tempDS.setPassword(PASSWORD);
tempDS.setMaxIdle(20);//池里不会被释放的最多空闲连接数量。设置为0时表示无限制。
tempDS.setMinIdle(5);
tempDS.setMaxWaitMillis(6000); // 设置最大等待时间
tempDS.setInitialSize(1);//池启动时创建的连接数量
tempDS.setMaxTotal(10); //最大连接数
tempDS.setRemoveAbandonedTimeout(6);// 当空闲连接耗尽,超过这个时间(秒),就会释放未关闭的连 接
Log.logger.severe("asicDataSource配置成功");
System.out.println("init..,");
return tempDS;
}
/**
* 断开DataSource
* @param
* @return
*/
protected static void destoryDataSource(){
try{
basicDS.close();
}
catch(Exception e){
e.printStackTrace();
}
basicDS=null;
}
/**
* 返回DataSource
* @return
*/
public static DataSource getDataSource(){
return basicDS;
}
/**
* 取得一个Connection
* 当已经是最大连接限制时warn
*
* @return
*/
public static Connection getConnection(){
try{
return basicDS.getConnection();
}
catch(Exception e){
e.printStackTrace();
return null;
}
}
/**
* 释放Connection
* @param con
*/
public static void freeConnection(Connection con){
if(con!=null){
try{
con.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String args[]){
Statement statement=null;
ResultSet rs=null;
Connection conn =null;
try {
conn = DbManager.getConnection();
if(conn != null){
statement = conn.createStatement();
rs = statement.executeQuery("select * from item");
int c = rs.getMetaData().getColumnCount();
while(rs.next()){
for(int i=1;i<=c;i++){
System.out.print(rs.getObject(i)+" ");
}
System.out.println();
}
rs.close();
}
DbManager.freeConnection(conn);
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null){
DbManager.freeConnection(conn);
}
}
}
}