package util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
public class JdbcUtil5 {
private static Properties map = new Properties();
private static DataSource ds=null;
static{
InputStream is = null;
try {
is =JdbcUtil4.class.getResourceAsStream("/util/conn.properties");
map.load(is);
ds=BasicDataSourceFactory.createDataSource(map);
} catch (Exception e) {
e.printStackTrace();
} finally{
if(is!=null)try {is.close();} catch (IOException e) {e.printStackTrace();}
}
}
public static ThreadLocal<Connection> tol = new ThreadLocal<Connection>();
public static Connection getConnection(){
try {
Connection conn =tol.get();
if(conn==null){
conn=ds.getConnection();
tol.set(conn);
}
return conn;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
public static void close(ResultSet rs,Statement stm,Connection conn){
if(rs!=null)try {rs.close();} catch (Exception e) {e.printStackTrace();}
if(stm!=null)try {stm.close();} catch (Exception e) {e.printStackTrace();}
if(conn!=null)try {conn.close();} catch (Exception e) {e.printStackTrace();}
}
}
java 实现jdbc连接mysql
最新推荐文章于 2024-03-07 17:27:54 发布