JDBC的工具类
使用JDBC时调用此工具类,首先更改类中相应的连接字段
- 使用
- 1.通过Connection获取conn连接
- 2.通过conn创建Statement对象
- 3.通过statement执行相应的SQL
- 4.释放资源
- 示例 见下方
⭐️:普通使用没问题但是:
1.遇到登陆场景使用statement会出现sql注入风险,应该使用prepareStatement对象锁定sql语句!!
2.大量访问应该使用连接池优化性能!!
//JDBC工具类
public class JDBCUtils {
private static final String driverClass;
private static final String url;
private static final String user;
private static final String password;
static {
driverClass="com.mysql.cj.jdbc.Driver";
url="jdbc:mysql:///jdbctest?serverTimezone=UTC";
user="root";
password="123456";
}
/**
* 注册驱动的方法
* @throws ClassNotFoundException
*/
public static void loadDriver() throws ClassNotFoundException {
Class.forName(driverClass);
}
/**
* 获得连接的方法
* @throws Exception
*/
public static Connection getConnection() throws Exception {
loadDriver();
return DriverManager.getConnection(url,user,password);
}
/**
* 资源释放
*/
public static void release(Connection connection, Statement statement){
if(connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
connection=null;
}
if (statement!=null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
statement=null;
}
}
public static void release(Connection connection, Statement statement, ResultSet resultSet){
if(connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
connection=null;
}
if (statement!=null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
statement=null;
}
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
resultSet=null;
}
}
//示例:
public void demo(){
Connection conn=null;
Statement statement=null;
try {
//1.获得连接
conn=JDBCUtils.getConnection();
//2.获得执行SQL的语句,执行SQL
statement=conn.createStatement();
String sql="INSERT user VALUES(null,'mmm','666','六六')";
if(statement.executeUpdate(sql)>0){
System.out.println("插入成功...");
};
} catch (Exception e) {
e.printStackTrace();
}finally {
//3.释放资源
JDBCUtils.release(conn,statement);
}
}