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语句,并返回生成的结果的对象

  • 相关阅读:
    第04组(64) 团队展示
    结对编程作业
    第一次个人编程作业
    寒假第二份大礼包
    热身礼包初体验,欢欢喜喜过大年
    第08组 Beta冲刺 (1/5)
    第08组 Alpha冲刺 总结
    第五次作业
    第08组 Alpha冲刺 (6/6)
    第08组 Alpha冲刺 (5/6)
  • 原文地址:https://www.cnblogs.com/sonerwx/p/10446300.html
Copyright © 2011-2022 走看看