A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 牛江伟 中级黑马   /  2019-8-14 15:56  /  795 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

创建数据库工具类:
package cn.itcast.util;

import java.io.IOException;

import java.sql.*;

import java.util.Properties;

public class DBUtil {

    static String url;

    static String user;

    static String password;

    //注册驱动

    static{

        try {

            Properties p =new Properties();

            p.load(DBUtil.class.getResourceAsStream("jdbc.properties"));

            String driver = p.getProperty("driver");

            url = p.getProperty("url");

            user = p.getProperty("user");

            password = p.getProperty("password");

            System.out.println(url);

            System.out.println(user);

            System.out.println(password);

            Class.forName(driver);

        } catch (ClassNotFoundException | IOException e) {

            e.printStackTrace();

        }

    }

    //获取连接
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
   
   
   
    //关闭资源
    public static void close(Statement stmt,Connection conn){
        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    //关闭资源
    public static void close(ResultSet rs,Statement stmt, Connection conn){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马