日期:2014-05-16 浏览次数:20615 次
jdbc读取属性文件连接数据库 源代码如下
?//======DbConnection类如下 package util;
?import java.io.InputStream;
import java.sql.Connection;
?import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
?import java.util.Properties;
?
public class DbConnection extends Properties {
private static final long serialVersionUID = 1L;
?private static DbConnection instance;
public static DbConnection getInstance() {
?if (instance != null) {
return instance;
?} else {
?makeInstance();
return instance;
}
}
private static synchronized void makeInstance() {
?if (instance == null) {
instance = new DbConnection();
?} }
?private DbConnection() {
InputStream is = getClass().getResourceAsStream("db.properties");
try {
?load(is);
?} catch (Exception e) {
System.out.println("错误:没有读取属性文件," + "请确认db.properties文件是否存在"); } }
?public static synchronized Connection getConnection() {
Connection conn = null;
String driverClassName = DbConnection.getInstance().getProperty("driver");
?String url = DbConnection.getInstance().getProperty("url");
String user = DbConnection.getInstance().getProperty("user");
String password = DbConnection.getInstance().getProperty("password");
?try {
Class.forName(driverClassName);
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
?System.out.println("数据库连接错误!");
e.printStackTrace();
?}
return conn; }
public static void close(
Connection con,
Statement st){ close(con); close(st);
?}
?public static void close(
Connection con,Statement st,ResultSet rs){
close(con,st); close(rs); }
?public static void close(Connection con){ try{ con.close(); }catch(Exception e){ } } public static void close(Statement st){ try{ st.close(); }catch(Exception e){ } } public static void close(ResultSet rs){ try{ rs.close(); }catch(Exception e){ } } }
//==============新建属性文件 如下注:属性文件的名称为:
db.properties 他们在同一级目录下
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost/jiraplugin
user=root password=root