日期:2014-05-20 浏览次数:20930 次
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* MYSQL数据库连接
*
* @author Rain
*
*/
public final class DBUtils {
private String url = null;
private String user = null;
private String password = null;
private static DBUtils instance = null;
private DBUtils() {
}
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError("数据库驱动加载错误");
}
}
public Connection getConnection() throws IOException, SQLException {
Properties prop = new Properties();
InputStream istream = DBUtils.class.getClassLoader().getResourceAsStream(
"MySQLConfig.properties");
try {
prop.load(istream);
} catch (IOException e1) {
throw new IOException("数据库配置加载错误");
}
url = "jdbc:mysql://" + prop.getProperty("MySQL.Local") + ":"
+ prop.getProperty("MySQL.Port") + "/" + prop.getProperty("MySQL.Name")
+ "?characterEncoding=utf8";
user = prop.getProperty("MySQL.User");
password = prop.getProperty("MySQL.Password");
Connection conn = null;
try {
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
throw new SQLException("数据库连接错误" + e);
}
conn.setAutoCommit(false);
return conn;
}
public static DBUtils getInstance() {
if (instance == null) {
synchronized (DBUtils.class) {
if (instance == null) {
instance = new DBUtils();
}
}
}
return instance;
}
// 数据库连接释放
public void dispose(ResultSet rs, Statement st, Connection conn) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null)
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}