返回

JavaWeb初识——JDBC:数据库连接与操作指南

后端

一、初识JDBC

JDBC(Java Database Connectivity)是Java编程语言中用于连接和操作数据库的API,它提供了一套标准的接口,使Java程序能够与各种数据库进行交互。

二、JDBC基本操作

  1. 连接数据库
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");

// 创建数据源工厂
DruidDataSourceFactory dataSourceFactory = new DruidDataSourceFactory();

// 设置数据源参数
dataSourceFactory.setDriverClass("com.mysql.jdbc.Driver");
dataSourceFactory.setUrl("jdbc:mysql://localhost:3306/test");
dataSourceFactory.setUsername("root");
dataSourceFactory.setPassword("password");

// 创建数据源
DruidDataSource dataSource = (DruidDataSource) dataSourceFactory.createDataSource();

// 获取连接
Connection connection = dataSource.getConnection();
  1. 查询数据库
// 创建Statement对象
Statement statement = connection.createStatement();

// 执行查询语句
ResultSet resultSet = statement.executeQuery("select * from user");

// 处理结果集
while (resultSet.next()) {
    int id = resultSet.getInt("id");
    String name = resultSet.getString("name");
    int age = resultSet.getInt("age");

    // 打印结果
    System.out.println("id: " + id + ", name: " + name + ", age: " + age);
}

// 关闭结果集
resultSet.close();

// 关闭Statement对象
statement.close();
  1. 插入数据
// 创建Statement对象
Statement statement = connection.createStatement();

// 执行插入语句
int rowCount = statement.executeUpdate("insert into user (name, age) values ('John', 20)");

// 关闭Statement对象
statement.close();

// 打印受影响的行数
System.out.println("受影响的行数:" + rowCount);
  1. 更新数据
// 创建Statement对象
Statement statement = connection.createStatement();

// 执行更新语句
int rowCount = statement.executeUpdate("update user set name = 'Mary' where id = 1");

// 关闭Statement对象
statement.close();

// 打印受影响的行数
System.out.println("受影响的行数:" + rowCount);
  1. 删除数据
// 创建Statement对象
Statement statement = connection.createStatement();

// 执行删除语句
int rowCount = statement.executeUpdate("delete from user where id = 2");

// 关闭Statement对象
statement.close();

// 打印受影响的行数
System.out.println("受影响的行数:" + rowCount);

三、总结

JDBC是JavaWeb开发中不可或缺的利器,它提供了连接和操作数据库的标准接口,使Java程序能够与各种数据库进行交互。通过JDBC,我们可以轻松地查询、插入、更新和删除数据库中的数据。

在实际开发中,我们通常会使用一些第三方框架来简化JDBC的使用,例如Spring JDBC和MyBatis。这些框架可以帮助我们更好地管理数据库连接池、执行SQL语句以及处理结果集,从而提高开发效率和降低出错概率。