public class JdbcUtils {
//定义Properties类
public static Properties prop = new Properties();
static{
try {
//获取配置文件
InputStream in = Thread.currentThread().getContextClassLoader().
getResourceAsStream("dbconfig.properties");
//加载配置文件
prop.load(in);
//加载数据库驱动
Class.forName(prop.getProperty("driverClassName"));
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
/*
* 获取数据库连接的方法
*/
public static Connection getConnection(){
try {
//获取数据库连接
return DriverManager.getConnection(prop.getProperty("url"),
prop.getProperty("username"),prop.getProperty("password"));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
配置文件:
dbconfig.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb1?useUnicode=true&characterEncoding=UTF8
username=root
password=649940992