package connect;
import java.sql.*;
import java.util.ArrayList;
public class DBConnection {
//存放Connection对象的数组,数组被看成连接池
static ArrayList<Connection> list=new ArrayList<Connection>();
//从连接池中取出一个连接对象
public synchronized static Connection getOneCon(){
//如果连接池中有连接对象
if(list.size()>0){
return list.remove(0);
}
//连接池没有连接对象创建连接放到连接池中
else{
for(int i=0;i<5;i++){
try {
//Class.forName("oracle.jdbc.driver.OracleDriver");
// Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=S_Md";
String userName = "140551124"; // 默认用户名
String userPwd = "140551124"; // 密码
Connection con=DriverManager.getConnection(dbURL, userName, userPwd);
// Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/adsystem","root","123456");
//Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","system","system");
list.add(con);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return list.remove(0);
}
}
//关闭结果集对象
public static void close(ResultSet rs){
try {
if(rs!=null)
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//关闭预处理语句
public static void close(PreparedStatement ps){
try {
if(ps!=null)
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//把连接对象放回连接池中
public synchronized static void close(Connection con){
if(con!=null)
list.add(con);
}
}