断弯刀

导航

DbUtil数据库连接

DbUtil数据库连接

package com.zjx.util;

import java.sql.Connection;
import java.sql.DriverManager;


public class DbUtil {

    /**
     * 获取连接
     * @return
     * @throws Exception
     */
    public Connection getCon() throws Exception{
        Class.forName(PropertiesUtil.getValue("jdbcName"));
        Connection con=DriverManager.getConnection(PropertiesUtil.getValue("dbUrl"), PropertiesUtil.getValue("dbUsername"), PropertiesUtil.getValue("dbPassword"));
        return con;
    }
    
    /**
     * 关闭数据连接
     * @param con
     * @throws Exception
     */
    public void closeCon(Connection con) throws Exception{
        if(con!=null){
            con.close();
        }
    }
    
    public static void main(String[] args) {
        DbUtil dbUtil=new DbUtil();
        Connection con=null;
        try {
            con=dbUtil.getCon();
            System.out.println("数据库连接成功");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("数据库连接失败");
        }finally {
            if(con!=null){
                try {
                    dbUtil.closeCon(con);
                    System.out.println("数据库连接成功关闭");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

 

posted on 2018-10-18 16:25  断弯刀  阅读(1297)  评论(0编辑  收藏  举报