方法一:直接读取db.properties.
package com.edusk.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class DBUtil {
private static String driver = "";
private static String url = "";
private static String username = "";
private static String password = "";
private Connection conn = null;
/*
* 静态代码块
*/
static{
Properties pro = new Properties();
try {
//这是将db.properties数据流放入内存中
InputStream ins = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
pro.load(ins);
driver=pro.getProperty("driver");
url=pro.getProperty("url");
username=pro.getProperty("username");
password=pro.getProperty("password");
ins.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public Connection getConnection() {
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 关闭链接
* @param con
* @param ps
* @param rs
*/
public static void close(Connection conn,PreparedStatement ps,ResultSet rs){
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
方法二:使用spring的配置:
/**
* 此方法最常用,也最简单;
* 不带参数意味着默认参数(applicationContext-config.xml配置文件中);
* @return Connection
* @throws Exception
*/
public static Connection getConnection() throws Exception {
WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
return DataSourceUtils.getConnection((DataSource)wac.getBean("dataSource"));
}