JDBC 工具类

package util;

import java.sql.*;

/**
 * JDBC的工具类
 */
final public class JdbcUtil {
    private static String user = "root";    // 数据库用户名
    private static String password = "";  // 数据库登录密码
    private static String url = "jdbc:mysql://127.0.0.1:3306/db_chat?useUnicode=true&characterEncoding=utf8";  //连接数据库地址

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");//加载驱动
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭数据库连接
     */
    public static void close(ResultSet rs, Statement stmt, Connection conn) {
        try {
            if (rs != null)
                rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (conn != null)
                        conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取数据库连接
     */
    public static Connection getConnection(){
        Connection conn = null;
        try {
            //连接数据库
            conn = DriverManager.getConnection(url,user,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

}
原文地址:https://www.cnblogs.com/wuyou/p/3751814.html