package com.ycx.util;
import java.sql.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.sql.PooledConnection;
public class ConnectionManager {
/*private static final String DRIVER_CLASS="oracle.jdbc.driver.OracleDriver";
private static final String DATABASE_URL="jdbc:oracle:thin:@localhost:1521:orcl";
private static final String DATABASE_USER="scott";
private static final String DATABASE_PASSWORD="flf";*/
/* private static final String DRIVER_CLASS="oracle.jdbc.driver.OracleDriver";
private static final String DATABASE_URL="jdbc:oracle:thin:@localhost:1521:orcl";
private static final String DATABASE_USER="scott";
private static final String DATABASE_PASSWORD="flf";*/
private static final String DRIVER_CLASS="com.mysql.jdbc.Driver";
private static final String DATABASE_URL="jdbc:mysql://localhost/ytx?useUnicode=true&characterEncoding=utf8";
private static final String DATABASE_USER="root";
private static final String DATABASE_PASSWORD="flf";
/**
* 返回连接
* @ return Connection
*/
public static Connection getConnection(){
Connection conn=null;
try{
Class.forName(DRIVER_CLASS);
conn=DriverManager.getConnection(DATABASE_URL,DATABASE_USER,DATABASE_PASSWORD);
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
public static Connection getPoolConnection() throws NamingException{
DataSource ds = null;
Connection conn = null;
InitialContext ctx = new InitialContext();
try{
ds=(DataSource)ctx.lookup("java:comp/env/jdbc/mysql");
conn = ds.getConnection();
// ctx = new InitialContext();
} catch(SQLException e){
e.printStackTrace();
}
return conn;
}
/**
* 关闭连接
* @param dbConnection
* Connection
*/
public static void closeConnection(Connection conn){
try{
if( conn!=null&&(!conn.isClosed())){
conn.close();
}
}catch(SQLException sqlEx){
sqlEx.printStackTrace();
}
}
/**
* 关闭结果集
* @param res
* ResultSet
*/
public static void closeResultSet(ResultSet rs){
try{
if(rs!=null){
rs.close();
rs=null;
}
}catch(SQLException e){
e.printStackTrace();
}
}
/**
* 关闭语句
* @param pStatement
* @ PreparedStatement
*/
public static void closePreparedStatement(PreparedStatement pstmt){
try{
if(pstmt!=null){
pstmt.close();
pstmt=null;
}
}catch(SQLException e){
e.printStackTrace();
}
}
public static void closeStatement(Statement pstmt){
try{
if(pstmt!=null){
pstmt.close();
pstmt=null;
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
/**
* public static synchronized Connection getConnection() throws DBAccessException{
* String driverClassName=Env.getInstance().getProperty("driver");
* String url=Env.getIstance().getProperty("url");
* String password=Env.getIstance().getProperty("password");
* String username=Env.getIstance().getProperty("username");
* Connection con=null;
* try{
* Class.forName(driverClassName);
* conn=DriverManager.getConnection(url,user,password);
* }catch(Exception e){e.printStackTrace()};
* }return conn
*/
JDBC-数据库连接工具类
最新推荐文章于 2023-06-01 01:34:23 发布