package base.jdbc;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.jdbc.Connection;
//工具类 连接类
public final class tools {
private static String url="jdbc:mysql://localhost:3306/jdbc";
private static String user="root";
private static String password="****";
private tools(){
//私有化
}
static{//只进行一次注册
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
throw new ExceptionInInitializerError(e);
}
}
//连接
public static Connection getConnection() throws SQLException{
return (Connection) DriverManager.getConnection(url, user, password);
}
//释放资源
public static void free(ResultSet rs,Statement st,Connection conn){
try {//抛出异常保证关闭
if(rs!=null)
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} finally {
try {
if(st!=null)
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} finally {
if(conn!=null){
try {
conn.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
JDBC-连接工具类
最新推荐文章于 2022-03-13 19:53:25 发布