数据库连接
package com.util;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
/**
* 1.节省资源 -- 单例工厂
* 2.开闭原则 -- 配置文件方式获取数据库信息
* 3.获取链接 -- getConnection
*
* 常见错误:
* ①配置文件必须在src下(classpath)
* ②配置信息中不要有多余的符号,例如""
* @author Administrator
*/
public class DBUtils {
private static DBUtils db;
private String url_;
private String user_;
private String password_;
private String driver_;
private DBUtils() {
try {
// 加载配置文件信息
Properties p = new Properties();
p.load(this.getClass().getClassLoader().getResourceAsStream("db.properties"));
// getProperty通过key值获取配置文件中的value值(返回值)
driver_ = p.getProperty("driver");
url_ = p.getProperty("url");
user_ = p.getProperty("user");
password_ = p.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
}
public static DBUtils getInstance() {
if(db == null) {
db = new DBUtils();
}
return db;
}
/**
* 获取数据库连接的方法
* @return 连接对象
* @throws SQLException
*/
public Connection getConnection() throws SQLException {
try {
Class.forName(driver_);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection conn = DriverManager.getConnection(url_, user_, password_);
return conn;
}
public void close(Connection conn) {
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void close(PreparedStatement ps) {
if(ps != null) {
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void close(ResultSet rs) {
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
网友评论