import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
//把连接数据库的 公共操作 写到方法中
public class DBUtil {
//常量
private final static String DRIVER = "com.mysql.jdbc.Driver";
private final static String URL = "jdbc:mysql://127.0.0.1:3306/db_0425";
private final static String USER = "root";
private final static String PASSWORD = "123456";
//第一次加载此类时,执行静态代码块,只执行一次
static{
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection(){
Connection connection = null;
try {
//String url = "jdbc:mysql://127.0.0.1:3306/db_0425";
connection = DriverManager.getConnection(URL,USER,PASSWORD);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
//关闭资源 null
public static void close(Connection connection, Statement statement, ResultSet set){
if (set != null) {
try {
set.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}