package com.curtis.mysql.dbc;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DatabaseConnection {
private static String DRIVER;
private static String URL;
private static String USER;
private static String PASSWORD;
private Connection connection = null;
static {
loadConfig();
}
public static void loadConfig() {
try {
InputStream inStream = DatabaseConnection.class.getResourceAsStream("/jdbc.properties");
Properties prop = new Properties();
prop.load(inStream);
// System.out.println(prop.toString());
DRIVER = prop.getProperty("mysql.driver");
URL = prop.getProperty("mysql.url");
USER = prop.getProperty("mysql.user");
PASSWORD = prop.getProperty("mysql.password");
} catch (Exception e) {
throw new RuntimeException("读取数据库配置文件异常!", e);
}
}
public Connection getConnection() {
try {
Class.forName(DRIVER);
this.connection = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
public void close() {
if (connection != null) {
try {
this.connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
DatabaseConnection connection=new DatabaseConnection();
System.out.println(connection.getConnection());
}
}
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://127.0.0.1:3306/c
mysql.user=root
mysql.password=
打开App,阅读手记
热门评论
1、配置文件读取
2、配置文件加载到Properties 对象中
3、取出配置文件中的内容
4、静态代码块优先执行
5、反射中的
Classs.forName("全类名")
为什么能这样加载,这个要重点去了解反射
6、数据库连接拿到后,后面一定要关闭
7、main
方法测试
8、mysql
驱动程序