apache提供的方便操作数据库的组件
核心
* QueryRunner对象
* query()/update()
* ResultSetHandler接口
* BeanHandler 针对查询一条记录的情况
* BeanListHandler 针对查询多条记录的情况
* ScalarHandler 针对获取第一条记录的指定列的情况
工具类 JdbcUtils
package com.wei.utils;
import java.sql.*;
public class JdbcUtils {
//数据库的驱动是需要执行一次
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/*
获取连接对象
*/
public static Connection getConnection() {
String url = "jdbc:mysql://localhost:3306/java2220?serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true";
try {
return DriverManager.getConnection(url, "root", "1234");
} catch (SQLException e) {
return null;
}
}
/**
* 关闭相关对象
* @param connection
* @param statement
*/
public static void close(Connection connection, Statement statement) {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection!= null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭对象
* @param connection
* @param statement
* @param resultSet
*/
public static void close(Connection connection, Statement statement, ResultSet resultSet) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
DBUtils
增删改查