jdbc连接用工具类

封装的是链接部分和关流部分

mysql8.0.13

public class JDBCUtils {
private JDBCUtils(){}
private static Connection con;
static{
try {
Class.forName("com.mysql.jdbc.Driver");
//2获得连接 对象
String url ="jdbc:mysql://localhost:3306/rwx?useSSl=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
String username="root";
String password="root";
con = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
throw new RuntimeException("数据库连接失败");
}

}
//定义静态方法 返回数据库的连接
public static Connection getConnection(){
return con;
}
//关资源
public static void close(Connection con, Statement stat){
if(stat!=null){
try {
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void close(Connection con, Statement stat,ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {

e.printStackTrace();
}
if(stat!=null){
try {
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}

猜你喜欢

转载自www.cnblogs.com/sonerwx/p/10446300.html