//DBUtil.java
package vill.util;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
/**
* @author vill
*
*/
public class DBUtil {
private static String driver;
private static String url;
private static String user;
private static String pwd;
//static语句块初始化字段信息
static{
try {
Properties properties = new Properties();
properties.load(DBUtil.class.getClassLoader().getResourceAsStream("vill/util/db.properties"));
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("username");
pwd = properties.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取与数据库的连接
* @return
* @throws Exception
*/
public static Connection getConnection() throws Exception{
Class.forName(driver);
return DriverManager.getConnection(url, user, pwd);
}
/**
* 关闭连接
* @param conn
* @param stm
* @param rs
*/
public static void closeConnection(Connection conn,Statement stm,ResultSet rs){
try {
if (conn != null)
conn.close();
if (stm != null)
stm.close();
if (rs != null)
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
System.out.println(new DBUtil().getConnection().getClass().getName());;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//配置文件db.properties
####oracle connection info
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:vill
username=vill
password=villvill
####mysql connection info
#driver=com.mysql.jdbc.Driver
#url=jdbc:mysql://localhost:3306/vill
#username=root
#password=root