1 package jdbc;
2
3 import java.sql.DriverManager;
4 import java.sql.SQLException;
5 import java.sql.*;
6
7 public class JdbcFirstDemo {
8 public static void main(String[] args) throws ClassNotFoundException, SQLException {
9 //1.加载驱动 固定写法
10 Class.forName("com.mysql.cj.jdbc.Driver");
11 // 2.连接 用户信息和 u r l
12 //支持中文编码 设定中文字符集utf8 ssl使用安全的连接
13 //useUnicode=true&characterEncoding=utf8&useSSL=true
14 String url ="jdbc:mysql://localhost:3306/jdbcstudy?useUnicode = true&characterEncoding = utf-8&useSSL = true&serverTimezone = GMT";
15 String username ="root";
16 String password ="root";
17 // 3.连接成功,返回一个数据库对象 Connection代表数据库
18 Connection connection = DriverManager.getConnection(url,username,password);
19 // 4.执行sql的对象Statement 执行sql的对象
20 Statement statement = connection.createStatement();
21 // 5.执行sql的对象去执行 sql 可能存在的结果 查看返回结果
22 String sql = "SELECT * FROM users";
23 ResultSet resultSet = statement.executeQuery(sql);//返回的结果集,封装了全部查询出来的结果
24
25 while (resultSet.next()) {
26 System.out.println("id=" + resultSet.getObject("id"));
27 System.out.println("name=" + resultSet.getObject("name"));
28 System.out.println("pwd=" + resultSet.getObject("password"));
29 System.out.println("email" + resultSet.getObject("email"));
30 System.out.println("birth=" + resultSet.getObject("birthday"));
31
32 }
33 //6.释放连接 从后往前 先开放的后关闭
34 resultSet.close();
35 statement.close();
36 connection.close();
37 }
38 }