JdbcUtil工具类
每次进行数据库操作时真正有用的代码很少,但是数据库访问的大量繁琐操作必须要编写,所以考虑引入工具类封装模板化的代码,以减少费管代码量,提交开发效率,精简代码。
public class JdbcUtil {
private JdbcUtil(){}
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取连接的方法
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:mysql:///test?serverTimezone=UTC","root","123456");
}
//关闭连接的方法
public static void close(ResultSet rs,Connection connection) throws SQLException {
try {
if (rs != null) {
rs.close();
}
}finally {
if (connection!=null){
connection.close();
}
}
}
//执行查询操作
public static ResultSet executeQuery(Connection connection, String sql, Object... params) throws SQLException {
ResultSet rs=null;
if (connection != null) {
PreparedStatement ps = connection.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
ps.setObject(i+1,params[i]);
}
}
rs=ps.executeQuery();
}
return rs;
}
//通用的增删改操作
public static int update(Connection connection, String sql, Object... params) throws SQLException {
int res=0;
if (connection != null) {
PreparedStatement ps=connection.prepareStatement(sql);
if (params != null&¶ms.length>0) {
for (int i = 0; i < params.length; i++) {
ps.setObject(i+1,params[i]);
}
}
res=ps.executeUpdate();
}
return res;
}
}
测试(添加数据):
public static void main(String[] args) {
Connection connection=null;
int res=0;
try {
connection=JdbcUtil.getConnection();
res = JdbcUtil.update(connection,"insert into tb_user(username,password) values(?,?)", "张三", "654321");
if (res > 0) {
System.out.println("插入成功");
}else {
System.out.println("插入失败");
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
JdbcUtil.close(null,connection);
}catch (Exception e){
e.printStackTrace();
}
}
}
mysql> select * from tb_user;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| 1 | CYP | 123456 |
+----+----------+----------+
1 row in set (0.49 sec)
mysql> select * from tb_user;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| 1 | CYP | 123456 |
| 2 | 张三 | 654321 |
+----+----------+----------+
2 rows in set (0.05 sec)