封装
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DBUtil {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Connection conn=null;
try{
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接
String url = "jdbc:mysql://127.0.1:3306/student_marks";
String user = "root";
String password = "123456";
return conn = DriverManager.getConnection(url, user, password);
}catch (ClassNotFoundException e){
throw new RuntimeException(e);
}
}
public static void close(Connection conn, Statement stmt){
//6.释放资源
//从小到大依次关闭
//分别对其try catch
try{
if(stmt!=null)stmt.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
try{
if(conn!=null)conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
实际调用