package com.zl.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DB {
private static final String DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final String URL="jdbc:sqlserver://localhost:1433;databasename=house";
private static final String USERNAME="sa";
private static final String PASSWORD="123";
static{
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/*
* 用内存传递数据( ThreadLocal 线程路径 )当工程一加载时就有一个内存空间
*/
private static ThreadLocal tL=new ThreadLocal();
public static Connection getConn() {
Object o=tL.get();
Connection con=null;
if(o==null){
try {
con=DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
tL.set(con);
}else{
con=(Connection)o;
}
return con;
}
/*
* 关闭连接
*/
public static void CloseCon(){
Object o=tL.get();
if(o!=null){
Connection con=(Connection)o;
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
tL.remove();
tL.set(null);
}
}
}
jdbc工具类
最新推荐文章于 2021-05-10 10:15:53 发布