Java系列-读取properties文件连接数据库

时间:2022-04-08 11:59:05

简介:将数据库的信息(数据库驱动driver、数据库url、用户名和密码)放在db.properties文件中,然后在java类中将这些数据取出来,做一个简单的数据库连接测试。

db.properties文件放在src目录下,源码:

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost/hibernate
username=root
password=123456

编写一个读取properties属性文件的方法类PropertiesUtils

PropertiesUtils.java

package com.xuxu.util;

import java.io.IOException;
import java.util.Properties;

public class PropertiesUtils {
static Properties property = new Properties();
public static boolean loadFile(String fileName){
try {
property.load(PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName));
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public static String getPropertyValue(String key){
return property.getProperty(key);
}
}

连接数据库的类DBUtil

DBUtil.java

package com.xuxu.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
public Connection conn= null;
public Statement stmt= null;
public ResultSet rs= null;

public DBUtil(){}

public static Connection getConnection(){
PropertiesUtils.loadFile("db.properties");
String url = PropertiesUtils.getPropertyValue("url");
String username = PropertiesUtils.getPropertyValue("username");
String password = PropertiesUtils.getPropertyValue("password");
String driver = PropertiesUtils.getPropertyValue("driver");

Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
if(conn==null){
System.out.println("error!!!!!");
}
return conn;
}

public static void main(String[] args) {
System.out.println(DBUtil.getConnection());
}
}

经测试,运行正常!