java 连接接数据库 中的代码 放到配置文件中

1.DButil.java

package com.jobproject.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

/**
* 连接数据库
* @author Administrator
*
*/
public class DButil {

//声明静态变量保存连接信息
private static String url;
private static String username;
private static String password;

/**
* 利用静态代码块
* 1、读取属性文件
* 2、加载驱动
*/
static
{
//绑定资源文件
ResourceBundle rb = PropertyResourceBundle.getBundle("com/jobproject/properties/config");
String driver = rb.getString("jdbc.driver");
url = rb.getString("jdbc.url");
username = rb.getString("jdbc.userName");
password = rb.getString("jdbc.password");
//加载驱动
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 获取连接
* @return
*/
public Connection getConnection(){
Connection conn = null;
try {
conn = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}

/**
* 关闭连接(当查询时)
*/
public static void freeAll(Connection conn, Statement st, ResultSet rs){
try {
if(conn != null){
conn.close();
}
if(st != null){
st.close();
}
if(rs != null){
rs.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* 关闭连接(当非查询时)
*/
public static void freeAll(Connection conn, Statement st){
freeAll(conn, st, null);
}

}

2.config.properties

#===============jdbc Connection===========
jdbc.url=jdbc:oracle:thin:@192.168.1.122:1521:xxxx
jdbc.userName=xxx
jdbc.password=xxxx
jdbc.driver=oracle.jdbc.driver.OracleDriver

上一篇:使用OneNote的COM组件,实现OCR功能。


下一篇:python迭代和切片