jdbc链接数据库学习记录

来源:互联网 发布:瑞尔森大学怎么样知乎 编辑:程序博客网 时间:2024/06/05 21:03

就直接代码上路:

public class DBUtils {    private static Properties props = new Properties();    private static ThreadLocal<Connection> connectionHolders = new ThreadLocal<Connection>();    static {        InputStream ips = DBUtils.class.getClassLoader().getResourceAsStream("com/gmai/verre/utils/db.properties");        //采用classloader的方式主要是通过他的getResourceAsStream方法去获取配置文件        try {            props.load(ips);//加载文档        } catch (IOException e) {            e.printStackTrace();            throw new RuntimeException("Deloading the property file is fail");        }    }    public synchronized static Connection getConnection() {//创建获取数据库对象,返回单一的连接对象        Connection conn= connectionHolders.get() ;        if (conn ==null ) {            conn =getConn();            connectionHolders.set(conn);        }        return conn;    }    public static Connection getConn() {// 获取数据库连接,返回连接结果        Connection conn = null;        try {            Class.forName(props.getProperty("driveName"));            conn = DriverManager.getConnection(props.getProperty("url"), props.getProperty("username"),                    props.getProperty("pwd"));        } catch (ClassNotFoundException e) {            e.printStackTrace();        } catch (SQLException e) {            e.printStackTrace();            throw new RuntimeException("The remote access connection failed");        }        return conn;    }    public static void close() {        Connection conn = connectionHolders.get();        if (conn != null) {            try {                conn.close();                connectionHolders.set(null);            } catch (SQLException e) {                e.printStackTrace();                throw new RuntimeException("Close the connection to the database is failed.");            }        }    }    public static PreparedStatement prepare(Connection conn, String sql) {        PreparedStatement ps=null;        try {            ps = conn.prepareStatement(sql);        } catch (SQLException e) {            e.printStackTrace();        }        return ps;    }    public static void close(PreparedStatement ps) {        try {        if(ps!=null) {            ps.close();            ps=null;            }        }catch (SQLException e) {            e.printStackTrace();        }    }}
原创粉丝点击