在靠近用户的地方部署容器
本工程教育(EngEd)计划由科支持。
在全球范围内即时部署容器。Section是经济实惠、简单而强大的。
免费入门。
Java JDBC入门
2021年2月3日
Java数据库连接(JDBC)是一个应用编程接口,它定义了Java程序如何连接和执行数据库查询。在本教程中,我们将创建一个简单的控制台应用程序,通过JDBC API执行数据库创建、读取、更新和删除操作。
前提条件
要继续学习,你将需要以下条件。
- 在你的机器上安装Java开发工具包JDK 11。
- 一个你选择的代码编辑器。我将使用Intellij社区版,它是免费的。
- 一些关于Java编程语言的基本知识。
- 在你的电脑上安装ApacheXAMPP。
- SQL的基本知识。
项目设置
- 在你的代码编辑器中,创建一个新的Java maven应用程序。
- 项目创建后,打开
pom.xml文件,添加mysql-connector依赖关系,如下图所示。mysql-connector使得从java应用程序连接到MySQL数据库成为可能。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>java-mysql</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- mysql-connector dependency -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>15</maven.compiler.source>
<maven.compiler.target>15</maven.compiler.target>
</properties>
</project>
- 在
src包中,创建3个Java文件,命名为Main.java,其中包含我们的main方法;Student.java,其中包含各种学生信息;MysqlAccess.java,其中包含我们的数据库访问源代码。
Student.java
这是一个普通的Java对象(POJO),将包含学生的信息。
public class Student {
private String name;
private String email;
private String course;
public Student(String name, String email, String course) {
this.name = name;
this.email = email;
this.course = course;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getCourse() {
return course;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public void setCourse(String course) {
this.course = course;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
", course='" + course + '\'' +
'}';
}
}
Student类有三个成员变量。name,course, 和email。它们代表学生的详细信息。Student类的构造函数使得每次创建该类的实例时都可以创建一个新的学生。getters和setters使得从类外访问类的成员变量成为可能。toString()方法返回类变量的一个字符串表示。
MysqlAccess.java
MysqlAccess.java类包含了处理数据库操作的方法。
它有以下的方法。
- **databaseConnection()**在我们的应用程序和MYSQL数据库之间建立一个数据库连接。
public void databaseConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
connect = DriverManager
.getConnection("jdbc:mysql://localhost/school?serverTimezone=UTC&"
+ "user=root&password=");
statement = connect.createStatement();
}
-
connect = DriverManager.getConnection("jdbc:mysql://localhost/school?serverTimezone=UTC&user=root&password=");设置数据库连接信息。 是数据库名称, 是数据库用户名,数据库密码是一个空白字符串``。schoolroot -
**getStudents()**方法从数据库中返回一个学生列表。
public List<Student> getStudents() {
List<Student> students = new ArrayList<>();
try {
resultSet = statement
.executeQuery("select * from school.students");
while (resultSet.next()) {
student_name = resultSet.getString("name");
student_email = resultSet.getString("email");
student_course = resultSet.getString("course");
Student student = new Student(student_name, student_email, student_course);
students.add(student);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return students;
}
-
resultSet = statement.executeQuery("select * from school.students");执行 查询,从数据库中获取所有学生,并将结果存储在 。SELECTresultSet -
while (resultSet.next())循环浏览结果集,以获得所有学生的数据返回。 -
**getStudentByEmail(String email)**从数据库中返回一个带有
SELECT查询中的电子邮件密码的学生。
public Student getStudentByEmail(String email) {
try {
resultSet = statement
.executeQuery("select * from school.students WHERE email= \'" + email + "\' LIMIT 1;");
while (resultSet.next()) {
student_name = resultSet.getString("name");
student_email = resultSet.getString("email");
student_course = resultSet.getString("course");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return new Student(student_name, student_email, student_course);
}
- **saveStudent(Student student)**将传递给该方法的一个新学生插入数据库。
public void saveStudent(Student student) {
try {
preparedStatement = connect
.prepareStatement("insert into students values (?, ?, ?)");
preparedStatement.setString(1, student.getName());
preparedStatement.setString(2, student.getCourse());
preparedStatement.setString(3, student.getEmail());
preparedStatement.executeUpdate();
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
- **deleteStudent(String email)**在数据库中删除一个带有
DELETE查询中传递的电子邮件的学生。
public void deleteStudent(String email) {
try {
preparedStatement = connect
.prepareStatement("delete from school.students where email= ? ; ");
preparedStatement.setString(1, email);
preparedStatement.executeUpdate();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
- **updateStudent(Student student, String email)**更新学生的信息,该学生的电子邮件被传递到
UPDATE查询中。
public void updateStudent(Student student, String email) {
try {
preparedStatement = connect
.prepareStatement("update students set name= ? where email= ? ;");
preparedStatement.setString(1, student.getName());
preparedStatement.setString(2, email);
preparedStatement.executeUpdate();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
- **close()**关闭数据库连接。
public void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
MySqlAccess 类的完整源代码显示如下。
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MySqlAccess {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
private String student_name;
private String student_email;
private String student_course;
public void databaseConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
connect = DriverManager
.getConnection("jdbc:mysql://localhost/school?"
+ "user=root&password=");
statement = connect.createStatement();
}
public List<Student> getStudents() {
List<Student> students = new ArrayList<>();
try {
resultSet = statement
.executeQuery("select * from school.students");
while (resultSet.next()) {
student_name = resultSet.getString("name");
student_email = resultSet.getString("email");
student_course = resultSet.getString("course");
Student student = new Student(student_name, student_email, student_course);
students.add(student);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return students;
}
public Student getStudentByEmail(String email) {
try {
resultSet = statement
.executeQuery("select * from school.students WHERE email= \'" + email + "\' LIMIT 1;");
while (resultSet.next()) {
student_name = resultSet.getString("name");
student_email = resultSet.getString("email");
student_course = resultSet.getString("course");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return new Student(student_name, student_email, student_course);
}
public void saveStudent(Student student) {
try {
preparedStatement = connect
.prepareStatement("insert into students values (?, ?, ?)");
preparedStatement.setString(1, student.getName());
preparedStatement.setString(2, student.getCourse());
preparedStatement.setString(3, student.getEmail());
preparedStatement.executeUpdate();
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
public void deleteStudent(String email) {
try {
preparedStatement = connect
.prepareStatement("delete from school.students where email= ? ; ");
preparedStatement.setString(1, email);
preparedStatement.executeUpdate();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void updateStudent(Student student, String email) {
try {
preparedStatement = connect
.prepareStatement("update students set name= ? where email= ? ;");
preparedStatement.setString(1, student.getName());
preparedStatement.setString(2, email);
preparedStatement.executeUpdate();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Main.java
在这个类中,我们将创建一个MySqlAccess 类的实例,并调用其各种方法来执行各种数据库查询。
import java.util.List;
public class Main {
public static void main(String args[]) throws Exception {
MySqlAccess dao = new MySqlAccess();
//Creates a database connection
System.out.println("Creating Database Connection");
dao.databaseConnection();
//Insert 2 students into the database
System.out.println("Inserting Students to the database");
Student peter = new Student("Peter John", "peter@gmail.com", "Computer Science");
Student cathy = new Student("Catherine Williams", "catherine@gmail.com", "Electrical engineering");
dao.saveStudent(peter);
dao.saveStudent(cathy);
//Get all Students from the database
System.out.println("Getting all students from the database");
List<Student> students = dao.getStudents();
for (Student student : students) {
System.out.println(student.toString());
}
//Get Student by email address
System.out.println("Getting the students by email");
Student student = dao.getStudentByEmail("peter@gmail.com");
System.out.println(student.toString());
//Updating student name
System.out.println("updating student name");
//Update Catherine Williams name to Catherine William
cathy.setName("Catherine William");
dao.updateStudent(cathy, cathy.getEmail());
//delete student
System.out.println("Deleting a student from the database");
dao.deleteStudent("peter@gmail.com");
//close the database connection
System.out.println("Closing the database connection");
dao.close();
}
}
创建数据库
- 从XAMPP控制面板中启动Apache和MySQL服务器。
- 在浏览器上的
http://localhost/phpmyadmin/网站上,创建一个数据库,名称为school。 - 在
school数据库中,创建一个名称为students的表,其字段name,类型为varchar,长度为100;email,类型为varchar,长度为100;course,类型为varchar,长度为100。

通过执行Main 类中的main 函数来运行该应用程序。
结论
现在你已经学会了如何从一个Java应用程序中执行各种数据库查询操作。你可以利用这些知识来建立更复杂的应用程序。
编码愉快!
同行评审的贡献者。Michael Barasa