package com.dxm.jdbcutil;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public class JDBCUtilsConfig {
private static Connection connection;
private static String driverClass;
private static String url;
private static String user;
private static String password;
public static Connection getConnection(){
return connection;
}
static{
try {
readConfig();
Class.forName(driverClass);
connection = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
throw new RuntimeException("数据库连接失败!");
}
}
private static void readConfig() throws IOException {
InputStream in = JDBCUtilsConfig.class.getClassLoader().getResourceAsStream("database.properties");
Properties pro = new Properties();
pro.load(in);
driverClass= pro.getProperty("driverClass");
url= pro.getProperty("url");
user= pro.getProperty("user");
password= pro.getProperty("password");
}
}
/*******************/
driverClass=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/mybase
user=root
password=1234
/******************/
package com.dxm.demo2;
import java.sql.Connection;
import com.dxm.jdbcutil.JDBCUtilsConfig;
public class TestJDBCUtils {
public static void main(String[] args) {
Connection connection = JDBCUtilsConfig.getConnection();
System.out.println(connection);
}
}