1.Java讀取properties文件建立數(shù)據源工具類:
package com.techstar.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtil {
private static String propertyURL = "com/techstar/DBconfic/conn.property";
private static String driver = null;
private static String url = null;
private static String userName = null;
private static String pwd = null;
//初始化連接信息
static {
init();
}
static void init() {
URL connPropertyUrl = new DBUtil().getClass().getClassLoader()
.getResource(propertyURL);
java.util.Properties pros = new java.util.Properties();
try {
pros.load(new java.io.FileInputStream(new File(connPropertyUrl.getPath())));
driver = (String)pros.get("driver");
url = (String)pros.get("db.url");
userName = (String)pros.get("db.username");
pwd = (String)pros.get("db.password");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Get connection
* @return
*/
public static Connection getDBConnection() {
Connection con = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, userName, pwd);
} catch (Exception ex) {
ex.printStackTrace();
}
return con;
}
/**
* Execute the sql
* @param sql
* @return
*/
public static String execute(String sql) {
Connection con = getDBConnection();
try {
java.sql.Statement st = con.createStatement();
java.sql.ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
String lValue = rs.getString(1);
return lValue;
}
} catch (SQLException e) {
e.printStackTrace();
}
return "";
}
}
2.properties文件配置數(shù)據源:
db.dialect=org.hibernate.dialect.OracleDialect
db.driverClassName=oracle.jdbc.driver.OracleDriver
db.url=jdbc:oracle:thin:@127.0.0.1:1521:lrmora9
db.username=username
db.password=pw