这是一个比较经典的数据库连接类,很多初学者在每个类里面都写数据库连接,这样的话,如果你的数据库一变动,或者连接变动,你都要手动去更改每个类。
为了让大家少干点体力劳动,我特意编写了一个连接管理类,希望新鸟用的上吧,老鸟就飘过吧~!!!!!
import java.sql.*;
/**
*
数据库连接管理类
* Created by 淘情网.
* User: 吴红军.
* Date: 11-12-26
* Time: 下午10:31
*/
public class DBConn {
private static String url = "jdbc:mysql://localhost:3306/jdbc";
private static String user = "root";
private static String password = "";
private DBConn() {
}
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
/**
* 获取数据库连接
* @return 数据库连接
* @throws SQLException
*/
public static Connection getConn() {
try{
return DriverManager.getConnection(url, user, password);
}catch (SQLException e){
throw new RuntimeException("获取连接错误!",e);
}
}
/**
* 释放连接和预编译语句
* @param rs 结果集对象
* @param st Statement对象
* @param conn 连接对象
*/
public static void free(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 (SQLException e) {
e.printStackTrace();
}
}
}
}
}