目录
1.JDBC操作示例回顾
我们学习MySQL数据库时 ,已经学习了JDBC来操作数据库, 但是JDBC操作太复杂了.
回顾一下JDBC的操作流程:
1. 创建数据库连接池 DataSource
2. 通过 DataSource 获取数据库连接 Connection
3. 编写要执⾏带? 占位符的 SQL 语句
4. 通过 Connection 及 SQL 创建操作命令对象 Statement
5. 替换占位符:指定要替换的数据库字段类型 , 占位符索引及要替换的值
6. 使⽤ Statement 执⾏ SQL 语句
7. 查询操作:返回结果集 ResultSet ,更新操作:返回更新的数量
8. 处理结果集
9. 释放资源
public class JDBCDemo1 {
public static void main(String[] args) throws SQLException {
// 假定数据库中有一个 student 表 (id, name), 往里面插入一个数据.
// 让用户通过控制台来输入学号和姓名.
Scanner scanner = new Scanner(System.in);
System.out.println("请输入学号: ");
int id = scanner.nextInt();
System.out.println("请输入姓名: ");
String name = scanner.next();
// 1. 创建 "数据源"
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf8&useSSL=false");
((MysqlDataSource) dataSource).setUser("root");
((MysqlDataSource) dataSource).setPassword("123456");
// 2. 和数据库服务器建立连接
Connection connection = dataSource.getConnection();
// 3. 构造 SQL 语句
String sql = "insert into jdbctest values(?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, id);
statement.setString(2, name);
// 4. 执行 SQL 语句. 返回值就是 "这次操作影响到几行"
int n = statement.executeUpdate();
System.out.println("n = " + n);
// 5. 释放必要的资源. 关闭连接.
statement.close();
connection.close();
}
}
查询语句:
// 查询
public class JDBCDemo3 {
public static void main(String[] args) throws SQLException {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入要查询的学号: ");
int studentId = scanner.nextInt();
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf8&useSSL=false");
((MysqlDataSource) dataSource).setUser("root");
((MysqlDataSource) dataSource).setPassword("123456");
Connection connection = dataSource.getConnection();
// 这里同样可以包含一些占位符.
String sql = "select * from jdbctest where id = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, studentId);
// 执行查询操作, 要使用 executeQuery. 返回值是一个 ResultSet 类型的对象. 表示了一个 "表格"
ResultSet resultSet = statement.executeQuery();
// 遍历结果集合
while (resultSet.next()) {
// 获取到这一行的 学号 列
int id = resultSet.getInt("id");
// 获取到这一行的 姓名 列
String name = resultSet.getString("name");
System.out.println("id: " + id + ", name: " + name);
}
// 释放资源.
resultSet.close();
statement.close();
connection.close();
}
}
从上述代码和操作流程可以看出 ,对于 JDBC 来说 ,整个操作非常的繁琐 ,我们不但要拼接每⼀个参数 ,⽽且还要按照模板代码的⽅式