前言
日常开发中,我们都习惯了使用ORM框架来帮我们操作数据库,本文复习、记录Java如何使用原生JDBC操作数据库
代码编写
封装几个简单方法
find查询方法
findOne查询方法
execute执行方法
package cn.huanzi.qch.util; import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.TimeInterval; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.sql.*; import java.util.ArrayList; import java.util.HashMap; /** * 原生jdbc操作数据库工具类 */ public class DbUtil { //数据库连接:地址、用户名、密码 private final String url; private final String username; private final String password; //Connection连接实例 private Connection connection; public DbUtil(String url, String username, String password){ this.url = url; this.username = username; this.password = password; } public DbUtil(String url, String username, String password, String driver){ this(url,username,password); //加载驱动 try { /* 同时需要引入相关驱动依赖 1、MySQL: com.mysql.cj.jdbc.Driver 2、Oracle: oracle.jdbc.driver.OracleDriver 3、pgsql: org.postgresql.Driver */ Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 获取 Connection 连接 */ private Connection getConnection() { if(connection == null){ try { connection= DriverManager.getConnection(url, username, password); connection.setAutoCommit(true); } catch (SQLException e) { System.err.println("获取Connection连接异常..."); e.printStackTrace(); } } return connection; } /** * 设置是否自动提交事务 * 当需要进行批量带事务的操作时,关闭自动提交手动管理事务,将会大大提高效率! */ private void setAutoCommit(boolean autoCommit){ try { this.getConnection().setAutoCommit(autoCommit); } catch (SQLException e) { e.printStackTrace(); } } /** * 关闭自动提交事务时,需要手动管理事务提交、回滚 */ private void commit(){ try { this.getConnection().commit(); } catch (SQLException e) { e.printStackTrace(); } } private void rollback(){ try { this.getConnection().rollback(); } catch (SQLException e) { e.printStackTrace(); } } /** * 关闭 Connection 连接 */ private void close(){ if(connection != null){ try { connection.close(); } catch (SQLException e) { System.err.println("关闭Connection连接异常..."); e.printStackTrace(); } } } /** * 查询 * 查询语句 */ public ArrayList<HashMap<String,Object>> find(String sql, Object[] params) { ArrayList<HashMap<String, Object>> list = new ArrayList<>(); //获取连接 Connection conn = this.getConnection(); PreparedStatement ps; ResultSet rs; try { //设置SQL、以及参数 ps = conn.prepareStatement(sql); if (params != null) { for (int i = 0; i < params.length; i++) { ps.setObject(i + 1, params[i]); } } //执行查询 rs = ps.executeQuery(); //获取查询结果 ResultSetMetaData rm = rs.getMetaData(); int columnCount = rm.getColumnCount(); //封装结果集 while (rs.next()) { HashMap<String, Object> map = new HashMap<>(columnCount); for (int i = 1; i <= columnCount; i++) { String name = rm.getColumnName(i).toLowerCase(); Object value = rs.getObject(i); map.put(name,value); } list.add(map); } } catch (Exception e) { System.err.println("执行 jdbcUtil.find() 异常..."); e.printStackTrace(); } return list; } public HashMap<String,Object> findOne(String sql, Object[] params){ ArrayList<HashMap<String, Object>> list = this.find(sql, params); return list.size() > 0 ? list.get(0) : null; } public ArrayList<HashMap<String,Object>> find(String sql) { return this.find(sql,null); } public HashMap<String,Object> findOne(String sql) { return this.findOne(sql,null); } /** * 执行 * 新增/删除/更新 等SQL语句 */ private boolean execute(String sql, Object[] params){ boolean flag = false; //获取连接 Connection conn = this.getConnection(); PreparedStatement ps; try { //设置SQL、以及参数 ps = conn.prepareStatement(sql); if (params != null) { for (int i = 0; i < params.length; i++) { ps.setObject(i + 1, params[i]); } } //执行 flag = ps.execute(); } catch (SQLException e) { System.err.println("执行 jdbcUtil.update() 异常..."); e.printStackTrace(); } return flag; } private boolean execute(String sql){ return this.execute(sql,null); } }
效果
运行main函数
public static void main(String[] args) { //获取实例 DbUtil dbUtil = new DbUtil("jdbc:mysql://localhost/jfinal_demo","root","123456"); // find查询 ArrayList<HashMap<String, Object>> list = dbUtil.find("select * from user"); for (HashMap<String, Object> map : list) { System.out.println(map); } System.out.println("----------------------------"); //execute执行、findOne查询 dbUtil.execute("delete from user where user_id = ?", new Object[]{"4"}); dbUtil.execute("insert into user values (?,?)", new Object[]{"4","王麻子"}); dbUtil.execute("update user set user_name = ? where user_id = ?", new Object[]{"王麻子子","4"}); HashMap<String, Object> map = dbUtil.findOne("select * from user where user_id = ?", new Object[]{"4"}); System.out.println(map); //关闭连接 dbUtil.close(); }
后记
原生JDBC操作数据库暂时先记录到这,后续再进行补充
PS:当需要进行批量带事务的操作时,将自动提交改成false,然后手动管理,将会大大提高效率!