JDBC访问MySQL8的示例
使用jdbc8.0.19访问MySQL8的注意事项. 与早期的MySQL版本不同, MySQL8增强了安全认证, 必须使用jdbc8+的版本, jdbc的类名改为com.mysql.cj.jdbc.Driver, 并且在jdbc的链接串中必须提供参数serverTimezone的值.
import java.sql.*;
import java.util.*;
public class MainJdbcDemo {
public static Connection connection;
public static boolean connectDb() {
if (connection != null) {
return true;
}
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/world?serverTimezone=GMT-8",
"java",
"123456");
} catch (Exception e) {
e.printStackTrace();
connection = null;
return false;
}
return true;
}
public static List<Student> getPersons() {
List<Student> persons = new ArrayList<>();
try {
Statement s = connection.createStatement();
String sql = "SELECT * from world.学生";
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
Student person = new Student(rs.getInt("学生id"), rs.getString("姓名"));
persons.add(person);
}
} catch (Exception e) {
System.out.println(e);
}
return persons;
}
public static void main(String[] args) {
boolean connectDb = connectDb();
if (connectDb == false) {
System.out.println("ConnectDB Failde!");
return;
}
List<Student> persons = getPersons();
for (int i = 0; i < persons.size(); i++) {
System.out.println(persons.get(i).getName());
}
}
}
class Student{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
数据库内容
运行结果
CS00
中文学生姓名