本文共 4863 字,大约阅读时间需要 16 分钟。
JDBC(Java DataBase Connectivity)是Java连接数据库的技术,提供一套操作所有关系型数据库的规则和接口,使得开发者可以通过一套代码与各种数据库进行交互。无论是MySQL、PostgreSQL还是 SQLite,JDBC都能统一管理这些数据库连接。
建立JDBC连接需要三个关键信息:
jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8&useSSL=false。root。root。Connection 是JDBC中最核心的接口,负责建立和管理数据库连接。它是Java程序与数据库交互的桥梁。以下是使用Connection的步骤:
Class.forName("com.mysql.jdbc.Driver");。DriverManager.getConnection(url, userName, password);。conn.close();。PreparedStatement 是用于执行动态SQL语句的接口。它支持占位符,让程序在运行时确定具体的SQL语句。例如:
String sql = "update tb_account set account_balance = 2000 where id = 1";try (PreparedStatement ps = conn.prepareStatement(sql)) { ps.setInt(1, 1); int rows = ps.executeUpdate(); System.out.println("rows = " + rows);} ResultSet 用于存储从数据库查询返回的结果集。它允许程序逐行读取数据:
ResultSet rs = ps.executeQuery();while (rs.next()) { int id = rs.getInt(1); String accountName = rs.getString(2); int balance = rs.getInt(3); System.out.println(id + "---" + accountName + "---" + balance);} 数据库连接池是一个容器,用于存储数据库连接对象。它的作用是减少频繁创建连接对象带来的性能消耗,提升数据库访问效率。连接池需要实现 javax.sql.DataSource 接口。
druid-1.0.9.jar。druid.properties 文件,配置连接池参数:driverClassName=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=UTF8&useSSL=falseusername=rootpassword=rootinitialSize=5maxActive=10maxWait=3000
public class DruidUtils { private static DataSource ds; static { try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties")) { Properties props = new Properties(); props.load(in); ds = DruidDataSourceFactory.createDataSource(props); } catch (Exception e) { throw new RuntimeException("连接池初始化失败"); } } public static DataSource getDataSource() throws Exception { return ds; } public static Connection getConnection() throws Exception { return ds.getConnection(); }}批处理允许一次性执行多个DML操作,确保所有操作要么全部成功,要么全部失败。使用批处理时,需确保事务已开启:
try (Connection conn = DruidUtils.getConnection()) { conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("delete from tb_account where id = ?"); ps.addBatch(); ps.addBatch(); ps.addBatch(); int[] rows = ps.executeBatch(); conn.commit();} 事务管理允许开发者控制数据库操作的原子性、持久性和一致性。通过设置 conn.setAutoCommit(false); 可以启用事务,确保异常时回滚所有操作。
DBUtils 是Apache 提供的JDBC工具库,简化了JDBC编码,降低了学习成本。它支持CRUD操作,并通过 QueryRunner 类简化SQL执行。
修改数据:
String sql = "update tb_account set account_balance = ? where id = ?";Object[] params = {new Account().getAccountBalance(), 1};int rows = runner.update(sql, params); 查询数据:
String sql = "select id, account_name, account_balance from tb_account";Listlist = runner.query(sql, new BeanListHandler (Account.class));list.forEach(account -> System.out.println(account));
BaseDAO 是一个通用的DAO类,封装了CRUD操作,减少代码重复。它支持:
save 方法。update 方法。delete 方法。getOne 和 getAll 方法。public interface AccountDAO { int saveAccount(String sql, Account account) throws Exception; int updateAccount(String sql, Account account) throws Exception; int deleteAccount(String sql, Integer id) throws Exception; List listAccount(String sql, Object... params) throws Exception; Account getAccountById(String sql, Object... params) throws Exception; long getAccountCount(String sql) throws Exception;} ###实现类
public class AccountDAOImpl extends BaseDAO implements AccountDAO { public int saveAccount(String sql, Account account) throws Exception { Object[] params = {account.getAccountName(), account.getAccountBalance()}; return update(sql, params); } // 其他方法类似} @Test 注解定义测试方法。@Testpublic void saveAccountTest() { Account account = new Account(-1, "王老五", 50001); try { int rows = dao.saveAccount("insert into tb_account(account_name, account_balance) values (?, ?)", account); System.out.println(rows > 0 ? "添加成功" : "添加失败"); } catch (Exception e) { e.printStackTrace(); }} 通过JDBC和DBUtils,我们掌握了对关系型数据库的标准操作。使用连接池优化数据库连接管理,批处理提升操作效率,BaseDAO 实现代码复用。这些技术结合使用,能够高效、简洁地完成数据库开发任务。
转载地址:http://upni.baihongyu.com/