Loading... #### 1.对于JAVA与数据库的连接操作我们可以专门定义一个工具类方便后面使用! ```java package 使用PreparedStatement实现CRUD.util; import java.io.IOException; import java.io.InputStream; import java.sql.*; import java.util.Properties; /** * @code Description * @code author 本当迷 * @code date 2022/7/14-18:14 */ public class JDBCUtils { // 获取数据库的连接 public static Connection getConnection() throws Exception { final InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties properties = new Properties(); properties.load(is); final String user = properties.getProperty("user"); final String password = properties.getProperty("password"); final String url = properties.getProperty("url"); final String driverClass = properties.getProperty("driverClass"); // 2.加载驱动 Class.forName(driverClass); // 3.获取连接 Connection connection = DriverManager.getConnection(url, user, password); System.out.println(connection); return connection; } // 关闭资源操作 public static void closeResource(Connection conn, Statement ps){ if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if(ps != null){ try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } // 关闭资源操作 public static void closeResource(Connection conn, Statement ps, ResultSet rs){ if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if(ps != null){ try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if(rs != null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } } ``` <div class="tip inlineBlock success"> 上面的程序中出现的配置文件 jdbc.properties ![](https://www.bdmcom.cn/usr/uploads/2022/07/258322633.png) * 数据库用户名 * 数据库密码 * mysql连接地址 * mysql驱动 使用配置文件的原因:因为我们项目上线都是把java程序打包为jar包的形式,为了后期项目因数据库的配置信息更换,我们把使用配置文件可以避免死数据的出现,加强程序的扩展性。 </div> #### 2.JDBC通用的增删改操作 ```java // 通用的增删改操作 public int update(String sql, Object ...args) { Connection conn = null; PreparedStatement ps = null; try { // 获取数据库连接 conn = JDBCUtils.getConnection(); // sql预编译 ps = conn.prepareStatement(sql); // 填充sql占位符 for(int i = 0; i < args.length; i++){ ps.setObject(i+1, args[i]); } // 执行sql语句 final int update = ps.executeUpdate(); return update; } catch (Exception e) { throw new RuntimeException(e); } finally { // 关闭资源 JDBCUtils.closeResource(conn, ps); } } ``` ##### 插入演示 ```java @Test public void testInsert(){ String sql = "insert user_table (user, password) values (?, ?)"; String user = "小当迷"; String password = "12345678"; final int insertCount = update(sql, user, password); if(insertCount > 0) System.out.println("插入成功!"); else System.out.println("插入失败!"); } ``` ##### 删除演示 ```java @Test void testDelete(){ String sql = "delete from user_table where user = ?"; String user = "小当迷"; final int deleteCount = update(sql, user); if(deleteCount > 0) System.out.println("删除成功!"); else System.out.println("删除失败"); } ``` ##### 修改演示 ```java @Test void testUpdate(){ String sql = "update user_table set password = ? where user = ?"; String user = "小当迷"; String password = "Abc123"; final int updateCount = update(sql, password, user); if(updateCount > 0) System.out.println("更新成功!"); else System.out.println("更新失败!"); } ``` #### 3.JDBC通用的查询操作 ```java public <T> List<T> selectList(Class<T> clazz, String sql, Object... args) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; final ArrayList<T> list; try { // 获取数据库连接 conn = JDBCUtils.getConnection(); // 预编译sql ps = conn.prepareStatement(sql); // 填充占位符 for (int i = 0; i < args.length; i++) { ps.setObject(i + 1, args[i]); } rs = ps.executeQuery(); // 获取元数据 final ResultSetMetaData metaData = rs.getMetaData(); // 获取字段的数目 final int columnCount = metaData.getColumnCount(); // 创建一个对象数组 list = new ArrayList<>(); while (rs.next()) { // 实例化clazz对象 final T t = clazz.getConstructor().newInstance(); // 遍历数据库字段 for (int i = 0; i < columnCount; i++) { // 获取字段值 final Object objectValue = rs.getObject(i + 1); // 获取字段别名 final String columnLabel = metaData.getColumnLabel(i + 1); // 利用反射给实例化对象赋值 final Field field = clazz.getDeclaredField(columnLabel); field.setAccessible(true); field.set(t, objectValue); } list.add(t); } return list; } catch (Exception e) { throw new RuntimeException(e); } finally { // 资源关闭 JDBCUtils.closeResource(conn, ps, rs); } } ``` ##### 查询演示: ```java @Test public void selectTest() { String sql = "select id, name, email from customers where id < ?"; final List<Customer> list = selectList(Customer.class, sql, 12); list.forEach(System.out::println); } ``` 最后修改:2022 年 07 月 19 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 0 如果文章有用,请随意打赏。
1 条评论
打个卡