使用JDBC实现学生信息的增删改查

一、数据库准备

1、新建数据库db_jdbc,设置字符集编码为utf-8
2、在数据库db_jdbc下新建表tb_stu,表结构如下所示:
在这里插入图片描述
建表语句为:

create table tb_stu(
		id int auto_increment comment '序号',
		className varchar(20) not null comment '班级',
		sno varchar(20) not null comment '学号',
		name archar(10) not null comment '姓名',
		sex varchar(4) not null comment '性别',
		age int comment '年龄',
		score decimal(5,2) comment '成绩',
		createTime datetime not null comment '创建时间',
		primary key(id)
)

二、构建项目

1、项目整体结构

在这里插入图片描述

1、创建Java项目Student_System_v1.0
2、在项目Student_System_v1.0下创建Folderlib,引入jar包,并加载其路径
在这里插入图片描述

三、创建工具类

1、连接数据库:BaseDao

在包com.student_system.utils下新建类:BaseDao,封装方法实现getConn()实现数据库的连接。

完整代码如下:

package com.student_system.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class BaseDao {
	private static String url = "jdbc:mysql://localhost:3306/db_jdbc?characterEncoding=utf-8";
	private static String user = "root";
	private static String password = "123456";
	//加载驱动
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	//获取连接
	public static Connection getConn() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	//测试连接是否成功
	public static void main(String[] args) {
		System.out.println(getConn());
	}
}

2、数据表操作:DBUtils

在包com.student_system.utils下新建类:DBUtils,封装方法实现updateData()实现数据更新(新增、修改、删除);封装方法实现queryData()实现数据查询。

完整代码如下:

package com.student_system.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtils {
	//更新数据
	public static int updateDate(String sql,Object...datas) {
		//获取连接
		Connection conn = BaseDao.getConn();
		int num = 0;
		try {
			//加载SQL语句
			PreparedStatement ps = conn.prepareStatement(sql);
			//设置占位符?代表的数据
			for(int i=0;i<datas.length;i++) {
				ps.setObject(i+1, datas[i]);
			}
			//执行SQL语句
			num = ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return num;
	}
	
	//查询数据
	public static ResultSet queryData(String sql,Object...datas) {
		//获取连接
		Connection conn = BaseDao.getConn();
		ResultSet rs = null;
		try {
			//加载SQL语句
			PreparedStatement ps = conn.prepareStatement(sql);
			//设置占位符?代表的数据
			for(int i=0;i<datas.length;i++) {
				ps.setObject(i+1, datas[i]);
			}
			//执行SQL语句
			rs = ps.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
}

四、创建实体类

创建数据表tb_stu对应的实体类,封装其字段(属性),提供公共的getXxx()setXxx()方法供用户访问:通过set方法可以将数据暂存在实体类中,通过get方法可以获取到暂存的数据。

在包com.student_system.model下新建类:Student,私有化属性,并提供公共访问方式(setXxx() / getXxx() / toString())完整代码如下:

package com.student_system.model;

public class Student {
	//序号
	private int id;
	//班级
	private String className;
	//学号
	private String sno;
	//姓名
	private String name;
	//性别
	private String sex;
	//年龄
	private int age;
	//成绩
	private double score;
	//创建时间
	private String createTime;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	public String getSno() {
		return sno;
	}
	public void setSno(String sno) {
		this.sno = sno;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public double getScore() {
		return score;
	}
	public void setScore(double score) {
		this.score = score;
	}
	public String getCreateTime() {
		return createTime;
	}
	public void setCreateTime(String createTime) {
		this.createTime = createTime;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", className=" + className + ", sno=" + sno + ", name=" + name + ", sex=" + sex
				+ ", age=" + age + ", score=" + score + ", createTime=" + createTime + "]";
	}
}

五、创建接口与实现类

1、在包com.student_system.service下新建接口StudentService,在其中创建实现学生信息增删改查的抽象方法。

package com.student_system.service;
//操作学生信息的接口
public interface StudentService {

}

2、在包com.student_system.service.impl下新建实现类StudentServiceImpl,实现接口StudentService,在其中具体实现接口中的抽象方法。

package com.student_system.service.impl;
import com.student_system.service.StudentService;
//实现接口的实现类
public class StudentServiceImpl implements StudentService {

}

六、实现查询所有学生信息功能

1、在接口StudentService中创建查询所有学生信息的抽象方法

//查询所有学生信息
public abstract List<Student> queryAll();

2、在实现类StudentServiceImpl中具体实现接口的中抽象方法queryAll()

@Override
public List<Student> queryAll() {
	String sql = "select * from tb_stu";
	//调用封装好的查询数据的方法
	ResultSet rs = DBUtils.queryData(sql);
	//创建集合存储查询到的数据
	List<Student> list = new ArrayList<>();
	try {
		while(rs.next()) {
			//创建实体类的对象
			Student stu = new Student();
			//将查询到的数据存储到实体类对象中
			stu.setId(rs.getInt("id"));
			stu.setClassName(rs.getString("className"));
			stu.setSno(rs.getString("sno"));
			stu.setName(rs.getString("name"));
			stu.setSex(rs.getString("sex"));
			stu.setAge(rs.getInt("age"));
			stu.setScore(rs.getDouble("score"));
			stu.setCreateTime(rs.getString("createTime"));
			//将实体类对象加入到集合中,集合中就拥有实体类对象中的所有数据
			list.add(stu);
		}
	} catch (SQLException e) {
		e.printStackTrace();
	}
	return list;
}

3、将查询到的数据显示到Swing窗体的表格中

在这里插入图片描述

将查询到数据显示在表格中的步骤:
1、调用接口得到查询得到的数据;
2、将查询得到的数据按规则存入二维数组中
在这里插入图片描述

关键代码:

//调用接口查询所有学生信息
	StudentService stuService = new StudentServiceImpl();
	List<Student> list = stuService.queryAll();
	
	//设置表格的标题
	String[] title = {"序号", "班级", "学号", "姓名", "性别", "年龄", "成绩", "创建时间"};
	//设置表格内容
	Object[][] data = new Object[list.size()][title.length];
	//将通过SQL语句查询到的数据存入二维数组
	for(int i=0;i<data.length;i++) {
		//将查询到的序号存储到二维数组的第i行第1列
		data[i][0] = list.get(i).getId();
		//将查询到的班级存储到二维数组的第i行第2列
		data[i][1] = list.get(i).getClassName();
		//将查询到的学号存储到二维数组的第i行第3列
		data[i][2] = list.get(i).getSno();
		//将查询到的姓名存储到二维数组的第i行第4列
		data[i][3] = list.get(i).getName();
		//将查询到的性别存储到二维数组的第i行第5列
		data[i][4] = list.get(i).getSex();
		//将查询到的年龄存储到二维数组的第i行第6列
		data[i][5] = list.get(i).getAge();
		//将查询到的成绩存储到二维数组的第i行第7列
		data[i][6] = list.get(i).getScore();
		//将查询到的创建时间存储到二维数组的第i行第8列
		data[i][7] = list.get(i).getCreateTime();
	}
	
	table = new JTable();
	table.setModel(new DefaultTableModel(
		data,
		title
	));
	scrollPane.setViewportView(table);
  • 10
    点赞
  • 62
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java JDBCJava语言用于连接和操作关系型数据库的API,可以通过它实现学生管理系统的增删改查功能。以下是一个简单的示例代码,演示如何使用Java JDBC实现学生管理系统的增删改查功能: 1.导入JDBC的jar包,连接数据库 ``` Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456"); ``` 2.实现查询功能 ``` public void query() { Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); String sql = "select * from student"; rs = stmt.executeQuery(sql); while (rs.next()) { System.out.println("id=" + rs.getInt("id") + ", name=" + rs.getString("name") + ", age=" + rs.getInt("age")); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } ``` 3.实现添加功能 ``` public void add(Student student) { PreparedStatement pstmt = null; try { String sql = "insert into student(name, age) values(?, ?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, student.getName()); pstmt.setInt(2, student.getAge()); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } ``` 4.实现删除功能 ``` public void delete(int id) { PreparedStatement pstmt = null; try { String sql = "delete from student where id=?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, id); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } ``` 5.实现修改功能 ``` public void update(Student student) { PreparedStatement pstmt = null; try { String sql = "update student set name=?, age=? where id=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, student.getName()); pstmt.setInt(2, student.getAge()); pstmt.setInt(3, student.getId()); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } ``` 完整代码如下: ``` import java.sql.*; public class StudentManager { private Connection conn; public StudentManager() { try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456"); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } public void query() { Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); String sql = "select * from student"; rs = stmt.executeQuery(sql); while (rs.next()) { System.out.println("id=" + rs.getInt("id") + ", name=" + rs.getString("name") + ", age=" + rs.getInt("age")); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } public void add(Student student) { PreparedStatement pstmt = null; try { String sql = "insert into student(name, age) values(?, ?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, student.getName()); pstmt.setInt(2, student.getAge()); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } public void delete(int id) { PreparedStatement pstmt = null; try { String sql = "delete from student where id=?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, id); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } public void update(Student student) { PreparedStatement pstmt = null; try { String sql = "update student set name=?, age=? where id=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, student.getName()); pstmt.setInt(2, student.getAge()); pstmt.setInt(3, student.getId()); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void main(String[] args) { StudentManager manager = new StudentManager(); manager.query(); manager.add(new Student("Tom", 18)); manager.query(); manager.update(new Student(1, "Jack", 20)); manager.query(); manager.delete(2); manager.query(); } } class Student { private int id; private String name; private int age; public Student(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } public Student(String name, int age) { this.name = name; this.age = age; } 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; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } ``` 在本示例,我们创建了一个StudentManager类,用于连接数据库实现学生管理系统的增删改查功能。在main方法,我们先查询了数据库学生信息,然后添加了一个新的学生,更新了一个学生的信息,删除了一个学生,最后再次查询了数据库学生信息,从而演示了增删改查功能的实现

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值