连接数据库工具类DBUtil

代码如下:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;

public class DBUtil {
    private static BasicDataSource ds;
    static {
        Properties prop = new Properties();
        try {
            prop.load(DBUtil.class.getClassLoader().getResourceAsStream("config.properties"));//类目录下要有对应的文件
            String className = prop.getProperty("classname");
            String url = prop.getProperty("url");
            String password = prop.getProperty("password");
            String username = prop.getProperty("username");

            ds = new BasicDataSource();
            ds.setDriverClassName(className);
            ds.setUrl(url);
            ds.setUsername(username);
            ds.setPassword(password);
            System.out.println("连接成功!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    public static void closeConnection(Connection conn) {
        try {
            conn.commit();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

 

posted @ 2018-01-10 11:22  admin_jh  阅读(173)  评论(0编辑  收藏  举报