@Test
public void test1() {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
// 1、加载驱动Class.forName("");
Class.forName("com.mysql.cj.jdbc.Driver");
// 2、获得连接对象Connection
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/study?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2b8", "root", "123456");
// 3、写sql语句
String sql = "select id,name,age,gender from student";
// 4、创建Statement(一艘船)
statement = connection.createStatement();
// 5、执行sql语句
// (1) 更新类(更改了表里面数据):delete/update/insert executeUpdate()
// 返回值:int,表示你影响的行数
// (2)查询(没有改变表里面数据): select executeQuery()
// 返回值:结果集ResultSet
resultSet = statement.executeQuery(sql);
List<Student> list = new ArrayList<>();
while(resultSet.next()) {//判断下一个有没有,如果没有返回false,如果有返回true,并且指向这一行
//当前resultSet指向第一行
//while循环每遍历一次,把这一行每个字段的值拿出来
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
String gender = resultSet.getString("gender");
Student student = new Student(id,name,age,gender);
list.add(student);
}
for (Student student : list) {
System.out.println(student);
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
// 6、关闭连接
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}