码迷,mamicode.com
首页 > 数据库 > 详细

jdbc连接用工具类

时间:2019-02-27 20:39:11      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:eva   对象   new   exce   静态代码块   jdbcutil   sele   red   set   

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

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();
}
}
}
}
}
}

由于使用了静态代码块,当类调用时直接执行,然后得到的con通过getConnection方法返回其他调用

调用封装的工具类

public class TestJDBCUtils {
public static void main(String[] args) throws SQLException {
Connection con = JDBCUtils.getConnection();
PreparedStatement pst = con.prepareStatement("select * from zhichu");

ResultSet rs = pst.executeQuery();
while(rs.next()){
System.out.println(rs.getString("zname"));
}
JDBCUtils.close(con, pst,rs);
}
}

调用后剩下的执行静态sql语句,并返回生成的结果的对象

jdbc连接用工具类

标签:eva   对象   new   exce   静态代码块   jdbcutil   sele   red   set   

原文地址:https://www.cnblogs.com/sonerwx/p/10446300.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!