注:内容仅供自娱自乐学习。
1.什么是JDBC
JDBC(Java Database Connectivity)是Java语言访问数据库的标准接口。通过JDBC,Java程序可以与各种不同类型的数据库进行交互,执行查询、更新和管理数据等操作。JDBC提供了一组类和接口,使得开发人员可以编写数据库无关的代码,从而方便地连接和操作数据库。通过JDBC,开发人员可以使用标准的SQL语句来操作数据库,实现数据的增删改查等功能。
2.了解JDBC中的API
2.1注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
在Java中,Class.forName("com.mysql.cj.jdbc.Driver"); 是用来加载特定类的方法。当调用这段代码时,Java虚拟机会尝试加载并初始化指定的类。在这种情况下,它会加载MySQL数据库的JDBC驱动程序类,以便在程序运行时可以与MySQL数据库建立连接并进行交互。
需要注意的是,在较新的JDBC版本中,也可以不显式调用Class.forName("com.mysql.cj.jdbc.Driver");来加载驱动程序,因为JDBC 4.0及以上版本支持自动加载驱动程序。但是,在一些旧版本(mysql5.0以下)或特定情况下,仍然需要显式加载驱动程序。
(一句话解释,就是告诉它我要连哪个数据库。)
2.2获取链接
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbcdb?characterEncoding=utf8&serverTimezone=Asia/Shanghai","root","1234");
这段代码的作用是通过JDBC驱动程序连接到本地MySQL数据库的jdbcdb数据库,使用用户名root`和密码1234,并将连接对象存储在connection变量中,以便后续在程序中使用该连接对象执行数据库操作。
值得注意的是在getConnection后的括号内应这样填写:数据库地址:jdbc:mysql://IP:端口号/数据库名?参数 三个参数分别为:url:数据库的地址 user: 数据库用户名 password: 数据库密码 。
2.3获取执行对象
Statement stat = connection.createStatement();
这行代码的作用是在已经建立的数据库连接上创建一个 Statement 对象,以便后续可以使用这个对象执行 SQL 查询或更新操作。
普通执行对象:使用createStatement()方法获取Statement对象。
预编译执行对象:使用prepareStatement()方法获取prepareStatemen对象。
预编译执行对象(可以调用存储过程):prepareCall()方法获取CallableStatement对象(使用较少)。
2.4拼写sql
String sql = "select * from t_user";
这行代码的作用是将 SQL 查询语句 `"select * from t_user"` 存储在变量 sql 中,以便后续可以使用该变量来执行这个查询操作。
2.5执行sql并且接收返回的结果
ResultSet rs = stat.executeQuery(sql);
这行代码的作用是执行之前定义的 SQL 查询语句,并将查询结果存储在 ResultSet 对象 rs 中,以便后续可以使用该对象来获取查询结果并进行进一步处理。
执行DML:执行insert,update,delete操作使用executeUpdate();返回int类型数据。
执行DQL:执行select操作使用executeQuery();返回的是ResultSet对象。
2.6处理结果
ArrayList<User> list = new ArrayList<>();
while(rs.next()){
User user = new User();
int userId = rs.getInt("user_id");
user.setUserId(userId);
String userName = rs.getString("user_name");
user.setUserName(userName);
list.add(user);
这段代码的作用是将从数据库查询结果中提取的用户数据逐行读取,并将每行数据封装到一个 User 对象中,然后将这些对象添加到 ArrayList 中,以便后续可以对这些数据进行进一步处理或展示。
其中需要提到的是:使用next()方法判断集合中是否还存在数据,回true:说明当前索引还有数据,同时索引下移返回false:说明结果没有数据了。getXXX(String 字段名):根据结果集中的字段名获取对应的数据getXXX(int 字段索引):根据结果集中的字段索引获取对应的数据(从1开始计算)。
2.7释放资源
rs.close();
stat.close();
connection.close();
return list;
rs.close(); // 关闭ResultSet对象。
stat.close(); // 关闭Statement对象。
connection.close(); // 关闭Connection对象。
return list; // 返回存储处理结果的ArrayList对象。
通过这段代码,确保在完成数据库操作后正确关闭 ResultSet、Statement 和 Connection 对象,以避免资源泄漏和提高系统性能。同时,将处理结果存储在 ArrayList 中,并将其返回供后续处理使用。
有了以上的例子和知识点,我们就可以着手自己写出利用JDBC对MYSQL数据库进行简单CRUD操作了。这是我们要操作的数据库的内容,数据库名字为:ljq,表的名字为:student。里面分别有id,name,gender,birthday四个数据。
3.在idea中进行操作
3.1添加jar
首先我创建了一个jdbc模块,并在它下面创建了一个文件夹lib用来放置jar,为什么要这么做呢?因为mysql-connector-java-8.0.20.jar 是 MySQL 官方提供的 Java 数据库连接器,用于在 Java 应用程序中连接和操作 MySQL 数据库。这个 JAR 文件包含了用于连接到 MySQL 数据库的驱动程序和相关类库。如果你想在 Java 项目中使用 MySQL 数据库,你需要将mysql-connector-java-8.0.20.jar 文件包含到你的项目中,并在代码中加载这个驱动程序来建立与 MySQL 数据库的连接。
3.2创建包和类
这是我们创建的包和类以及接口 其中main用来模拟客户端发送请求,Dao为持久化层,用来操作数据库,Service为业务层 用来处理业务和事务 Controller为控制层 用来接收客户端的请求,pojo为实体类。一切准备就绪,开始书写代码。
3.3代码
StudentController
package com.ljq.controller;
import com.ljq.pojo.Student;
import com.ljq.service.StudentService;
import com.ljq.service.impl.StudentServiceImpl;
import java.util.List;
public class StudentController {
//控制层 用于接收客户端的请求
StudentService StudentService = new StudentServiceImpl();
public List<Student> findAll(){
List<Student> list = StudentService.findAll();
return list;
}
public Student findById(Integer id){
return StudentService.findById(id);
}
public Boolean addStudent(Student student){
return StudentService.addStudent(student);
}
public Boolean editStudent(Student student){
return StudentService.editStudent(student);
}
public Boolean deleteById(Integer id){
return StudentService.deleteById(id);
}
}
StudentDaoImpl
package com.ljq.dao.impl;
import com.ljq.dao.StudentDao;
import com.ljq.pojo.Student;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class StudentDaoImpl implements StudentDao {
@Override
public List<Student> findAll() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ljq?characterEncoding=utf8&serverTimezone=Asia/Shanghai","root","1234");
Statement stat = connection.createStatement();
String sql = "select * from student";
ResultSet resultSet = stat.executeQuery(sql);
List<Student> list = new ArrayList<>();
while(resultSet.next()){
Student student = new Student();
student.setStudentId(resultSet.getInt("student_id"));
student.setStudentName(resultSet.getString("student_name"));
student.setStudentGender(resultSet.getString("student_gender"));
student.setStudentBirthday(resultSet.getDate("student_birthday"));
list.add(student);
}
resultSet.close();
stat.close();
connection.close();
return list;
}
@Override
public Student findById(Integer id) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ljq?characterEncoding=utf8&serverTimezone=Asia/Shanghai","root","1234");
PreparedStatement ps = connection.prepareStatement("select * from student where student_id = ?");
ps.setInt(1,id);
ResultSet resultSet = ps.executeQuery();
Student student = null;
while(resultSet.next()){
student = new Student();
student.setStudentId(resultSet.getInt("student_id"));
student.setStudentName(resultSet.getString("student_name"));
student.setStudentGender(resultSet.getString("student_gender"));
student.setStudentBirthday(resultSet.getDate("student_birthday"));
}
resultSet.close();
ps.close();
connection.close();
return student;
}
@Override
public Integer addStudent(Student student) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ljq?characterEncoding=utf8&serverTimezone=Asia/Shanghai","root","1234");
PreparedStatement ps = connection.prepareStatement("insert into student values(0,?,?,?)");
ps.setString(1,student.getStudentName());
ps.setString(2,student.getStudentGender());
ps.setDate(3,new java.sql.Date(student.getStudentBirthday().getTime()));
int i = ps.executeUpdate();
ps.close();
connection.close();
return i;
}
@Override
public Integer editStudent(Student student) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ljq?characterEncoding=utf8&serverTimezone=Asia/Shanghai","root","1234");
PreparedStatement ps = connection.prepareStatement("update student set student_name=?,student_gender=?,student_birthday=?" +
"where student_id = ?");
ps.setString(1,student.getStudentName());
ps.setString(2,student.getStudentGender());
ps.setDate(3,new java.sql.Date(student.getStudentBirthday().getTime()));
ps.setInt(4,student.getStudentId());
int i = ps.executeUpdate();
ps.close();
connection.close();
return i;
}
@Override
public Integer deleteById(Integer id) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ljq?characterEncoding=utf8&serverTimezone=Asia/Shanghai","root","1234");
PreparedStatement ps = connection.prepareStatement("delete from student where student_id = ?");
ps.setInt(1,id);
int i = ps.executeUpdate();
ps.close();
connection.close();
return i;
}
}
StudentDao
package com.ljq.dao;
import com.ljq.pojo.Student;
import java.sql.SQLException;
import java.util.List;
public interface StudentDao {
//1.查询所有
List<Student> findAll() throws SQLException, ClassNotFoundException;
//2.根据id查询
Student findById(Integer id)throws SQLException, ClassNotFoundException;
//3。添加信息
Integer addStudent(Student student)throws SQLException, ClassNotFoundException;
Integer editStudent(Student student)throws SQLException, ClassNotFoundException;
Integer deleteById(Integer id)throws SQLException, ClassNotFoundException;
}
StudentMain
package com.ljq.main;
import com.ljq.controller.StudentController;
import com.ljq.pojo.Student;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
public class StudentMain {
//模拟客户端,发送请求。
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
StudentController studentController = new StudentController();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
while (true){
System.out.println("1.查询所有的学生信息");
System.out.println("2.根据id查询信息");
System.out.println("3.新增学生信息");
System.out.println("4,修改学生信息");
System.out.println("5.删除学生信息");
System.out.println("请输入你的选择");
int i = sc.nextInt();
switch (i)
{
case 1 :
List<Student> list = studentController.findAll();
for (Student student : list) {
System.out.println(student);
}
break;
case 2 :
System.out.println("请输入id");
int id = sc.nextInt();
Student student = studentController.findById(id);
if(student != null){
System.out.println(student);
}
else {
System.out.println("此学生不存在");
}
break;
case 3:
System.out.println("请输入学生的姓名");
String inputName = sc.next();
System.out.println("请输入学生的性别");
String inputGender = sc.next();
System.out.println("请输入学生的出生日期");
String inputBirthday = sc.next();
Student addStudent = new Student();
Date parse = sdf.parse(inputBirthday);
addStudent.setStudentName(inputName);
addStudent.setStudentGender(inputGender);
addStudent.setStudentBirthday(parse);
Boolean addFlag = studentController.addStudent(addStudent);
if(addFlag){
System.out.println("添加成功");
}else {
System.out.println("添加失败");
}
break;
case 4:
System.out.println("输入您想修改的学生id");
int editId = sc.nextInt();
Student editStudent = studentController.findById(editId);
if( editStudent != null ){
System.out.println("学生的原名为:"+editStudent.getStudentName()+";请输入新的名字");
System.out.println("请输入学生的姓名");
editStudent.setStudentName(sc.next());
System.out.println("学生的原性别为:"+editStudent.getStudentGender()+";请输入新的性别");
editStudent.setStudentGender(sc.next());
String format = sdf.format(editStudent.getStudentBirthday());
System.out.println("学生的出生日期为:"+format+";请输入新的生日");
String editBirthday = sc.next();
Date parse1 = sdf.parse(editBirthday);
editStudent.setStudentBirthday(parse1);
Boolean editFlag = studentController.editStudent(editStudent);
if(editFlag){
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
}else{
System.out.println("该学生不存在!");
}
break;
case 5:
System.out.println("请输入删除的id");
int deleteId = sc.nextInt();
Boolean deleteFlag = studentController.deleteById(deleteId);
if(deleteFlag){
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
}
}
}
}
pojo
package com.ljq.pojo;
import java.util.Date;
public class Student {
private Integer studentId;
private String studentName;
private String studentGender;
private Date studentBirthday;
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentGender() {
return studentGender;
}
public void setStudentGender(String studentGender) {
this.studentGender = studentGender;
}
public Date getStudentBirthday() {
return studentBirthday;
}
public void setStudentBirthday(Date studentBirthday) {
this.studentBirthday = studentBirthday;
}
@Override
public String toString() {
return "Student{" +
"studentId=" + studentId +
", studentName='" + studentName + '\'' +
", studentGender='" + studentGender + '\'' +
", studentBirthday=" + studentBirthday +
'}';
}
}
StudentServiceImpl
package com.ljq.service.impl;
import com.ljq.dao.StudentDao;
import com.ljq.dao.impl.StudentDaoImpl;
import com.ljq.pojo.Student;
import com.ljq.service.StudentService;
import java.sql.SQLException;
import java.util.List;
public class StudentServiceImpl implements StudentService {
StudentDao studentDao = new StudentDaoImpl();
@Override
public List<Student> findAll() {
List<Student> list = null;
try {
list = studentDao.findAll();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return list;
}
@Override
public Student findById(Integer id) {
Student student = null;
try {
student = studentDao.findById(id);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return student;
}
@Override
public Boolean addStudent(Student student) {
Integer i = null;
try {
i = studentDao.addStudent(student);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (i != null && i > 0) {
return true;
} else {
return false;
}
}
public Boolean editStudent(Student student) {
Integer i = null;
try {
i = studentDao.editStudent(student);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (i != null && i > 0) {
return true;
} else {
return false;
}
}
@Override
public Boolean deleteById(Integer id) {
Integer i = null;
try {
i = studentDao.deleteById(id);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (i != null && i > 0){
return true;
}else {
return false;
}
}
}
StudentService
package com.ljq.service;
import com.ljq.pojo.Student;
import java.util.List;
public interface StudentService {
List<Student> findAll();
Student findById(Integer id);
Boolean addStudent(Student student);
Boolean editStudent(Student student);
Boolean deleteById(Integer id);
}
以上为具体代码,可以基本实现对数据库的增删改查。