zoukankan      html  css  js  c++  java
  • 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();
    }
    }
    }
    }
    }
    }

    由于使用了静态代码块,当类调用时直接执行,然后得到的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语句,并返回生成的结果的对象

  • 相关阅读:
    gulp之压缩合并MD5清空替换加前缀以及自动编译自动刷新浏览器大全
    HTML5之文件API
    Angular2之路由学习笔记
    nodejs之主机不能访问到虚拟机的web服务器
    学习CSS3动画(animation)
    jQuery之ajax错误调试分析
    Angular2之管道学习笔记
    css3之3D魔方动画(小白版)
    关于二维网格导入autodyn的问题
    两个橡胶球自由落体撞击弹性板
  • 原文地址:https://www.cnblogs.com/sonerwx/p/10446300.html
Copyright © 2011-2022 走看看