connectionfactory.java

来自「JDBC连数据库,这是一门很基初的技术,一定要好好研究」· Java 代码 · 共 47 行

JAVA
47
字号
package com.allanlxf.jdbc.util;

import java.sql.*;
import java.io.*;
import java.util.Properties;

public class ConnectionFactory
{
    private static Properties config = new Properties();
    
    static
    {
        InputStream in = ConnectionFactory.class.getResourceAsStream("db-config.properties");
        if(in == null)
        {
            throw new ExceptionInInitializerError("no file:db-config.properties found error!");
        }        
        
        try
        {
            config.load(in);
            in.close();
        }catch(IOException e)
        {
            e.printStackTrace();
            throw new ExceptionInInitializerError("failed to load file!");
        }
    }
    
    public static Connection getConnection() throws SQLException
    {
        try
        {
            String driverClassName = config.getProperty("driverClassName");
            String jdbcURL = config.getProperty("jdbcURL");
            String userName = config.getProperty("userName");
            String password = config.getProperty("password");
            
            Class.forName(driverClassName);
            return DriverManager.getConnection(jdbcURL, userName, password);
        }catch(ClassNotFoundException e)
        {
            e.printStackTrace();
            throw new SQLException(e.getMessage());
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?