【JavaEE高级】默写JDBC连接代码

默写JDBC连接代码

默写流程

  1. 核心流程
// 1 加载驱动类

// 2 获取连接

// 3 SQL 预处理

// 4 执行 SQL

// 5 获取结果集

// 6 关闭连接
  1. 补全流程代码

// 1 加载驱动类
Class.forName("com.mysql.cj.jdbc.Driver");

// 2 获取连接
// 2.1 加载配置
Properties prop = new Properties();
prop.setProperty("user", "root");
prop.setProperty("password", "password");
// 2.2 创建连接
Connection connection = DriverManager.getConnnection(
  prop,
  "jdbc:mysql://localhost:3306/jhome?characterEncoding=utf-8"
);

// 3 SQL 预处理
PreparedStatement ps = connection.prepareStatement(
  "select * from user where name = ?"
);
ps.setString(1, "测试");

// 4 执行 SQL
ResultSet rs = ps.executQuery();

// 5 获取结果集
while(rs.next()) {
  Long id = rs.getLong("id");
  String name = rs.getString("name");
  System.out.printf("id: %s, name: %s", id, name);
}

// 6 关闭连接
rs.close();

  1. 放到idea里运行, 并修改错误
// 1 加载驱动类
Class.forName("com.mysql.cj.jdbc.Driver");

// 2 获取连接
// 2.1 加载配置
Properties prop = new Properties();
prop.setProperty("user", "root");
prop.setProperty("password", "fc4fcafd-e86d-4fda-9a96-60147e94cc0f");
// 2.2 创建连接
Connection connection = DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/jhome?characterEncoding=utf-8",
        prop

);

// 3 SQL 预处理
PreparedStatement ps = connection.prepareStatement(
        "select * from user where name = ?"
);
ps.setString(1, "测试");

// 4 执行 SQL
ResultSet rs = ps.executeQuery();

// 5 获取结果集
while(rs.next()) {
    Long id = rs.getLong("id");
    String name = rs.getString("name");
    System.out.printf("id: %s, name: %s", id, name);
}

// 6 关闭连接
rs.close();

默写的好处

  1. 熟悉英文单词的拼写, 减少英文拼写错误
  2. 调动大脑去回忆, 提高神经元关联, 变为真正的记住
  3. 细节, 在默写的时候你会发现很多细节是你没注意到的
  4. 默写完并且注意细节之后, 可以延伸出更多扩展信息的思考

你可能感兴趣的:(mybatis,java)