package bean;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBUtil {
static {
//MySQL 5.7及以下使用的代码
String driverClass="com.mysql.jdbc.Driver";
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 加载数据库驱动
}
public DBUtil() {
// TODO Auto-generated constructor stub
}
//获取数据库连接
public static Connection getConnection() {
String url="jdbc:mysql://localhost:3307/stu";
String username = "root";
String password = "";
Connection conn = null;
try {
conn = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//获取静态语句操作对象
public static Statement getStatement(Connection conn) {
Statement stat = null;
try {
stat = conn.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stat;
}
//释放资源
public static void closeAll(Connection connection, Statement statement,ResultSet resultSet){
try {
if (resultSet!=null){
resultSet.close();
}
if (connection!=null){
connection.close();
}
if (statement!=null){
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//释放资源 (方法重载)
public static void close(Connection connection, Statement statement){
try {
if (connection!=null){
connection.close();
}
if (statement!=null){
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
评论区