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

}

 

posted @ 2014-05-25 23:05  无忧之路  阅读(408)  评论(0编辑  收藏  举报
无忧之路