连接数据库

来源:互联网 发布:雪茄属于淘宝禁售品吗 编辑:程序博客网 时间:2024/05/28 11:28
    private static final String url="jdbc:mysql://localhost:3306/数据库名";
    private static final String user="root";
    private static final String password="密码";
    //加载驱动
    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //创建连接
    public static Connection getConnection() throws SQLException{
        return DriverManager.getConnection(url,user,password);
    }
    //关闭连接
    public static void close(ResultSet res,PreparedStatement sta,Connection conn) throws SQLException{
        if(res!=null){
            res.close();
            }
        if(sta!=null){
            sta.close();
            }
        if(conn!=null){
            conn.close();
            }
    }
0 0
原创粉丝点击