一.JDBC 实例

  1. //1. 加载一个Driver驱动
  2. Class.forName("com.mysql.cj.jdbc.Driver"); // 8.0的驱动类
  3. //Class.forName("com.mysql.jdbc.Driver"); // 5.X 驱动类
  4. //2. 创建数据库连接(Connection)
  5. String url = "jdbc:mysql://localhost:3306/i-news?serverTimezone=Asia/Shanghai";
  6. String user = "root";
  7. String password = "123456";
  8. Connection conn = DriverManager.getConnection(url,user,password); // 多态
  9. //3. 创建SQL命令发送器Statement
  10. Statement st = conn.createStatement();
  11. //4. 通过Statement发送SQL命令并得到结果
  12. String sql = "select * from admin";
  13. ResultSet rs = st.executeQuery(sql);
  14. //5. 处理SQL结果(select语句)
  15. while (rs.next()) {
  16. System.out.print(rs.getString("id") + "\t");
  17. System.out.println(rs.getString("username"));
  18. }
  19. //6. 关闭数据库资源
  20. rs.close();
  21. st.close();
  22. conn.close();