您的位置:首页 > 编程语言 > Java开发

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

2013-07-18 22:05 597 查看
用配置文件连接数据库

1. Eclipse中,在src目录下建立db.properties文件,在里面配置数据库连接所需的 Driver,url,user,possword ,注意等号左右不能空格
如:

driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost:1433;databaseName=restrant
user=root
password=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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐