java调用properties配置文件连接数据库

时间:2023-01-30 11:55:56
    用配置文件连接数据库
1. Eclipse中,在src目录下建立db.properties文件,在里面配置数据库连接所需的      Driver,url,user,possword ,注意等号左右不能空格 如:
driver=com.microsoft.sqlserver.jdbc.SQLServerDriverurl=jdbc:sqlserver://localhost:1433;databaseName=restrantuser=rootpassword=110

2.写一个数据库连接类
ConnDB类
package tools;
import java.sql.*;
public class ConnDB {

public Connection conn = null;
public Statement stmt = null;
public ResultSet rs = null;
public ConnDB(){ }
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
public static Connection getConnection() {

PropertiesUtils.loadFile("/db.properties");
String url = PropertiesUtils.getPropertyValue("url");
String user = PropertiesUtils.getPropertyValue("user");
String password = PropertiesUtils.getPropertyValue("password");
String driver = PropertiesUtils.getPropertyValue("driver");

Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,user,password);
}
catch (Exception ee) {
ee.printStackTrace();
}
if (conn == null) {
System.err.println("error~~~~~~~~~~~~~~~" );
}
return conn;
}



PropertiesUtils 类 供读取db.properties配置文件
package tools;

import java.io.IOException;
import java.util.Properties;
public class PropertiesUtils {
//产生一个操作配置文件的对象
static Properties prop = new Properties();
/**
* @param fileName 需要加载的properties文件,文件需要放在src根目录下
* 是否加载成功
*/
public static boolean loadFile(String fileName){
try {
prop.load(PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName));
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 根据KEY取回相应的value

*/
public static String getPropertyValue(String key){
return prop.getProperty(key);
}
}