1、请编程实现基于数据库的学生信息管理程序,程序的功能有:显示所有学生、新增学生、删除学生、修改学生、查找学生(根据学号、姓名、班级、性别、专业、学院等),程序采用命令行方式。 2、请编程实现把从数据库中查询出的学生信息记录集(ResultSet)中的记录转换为学生对象。
建立与数据库之间的连接会话,所有的操作都是基于这个会话基础上进行的
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
//1、请编程实现基于数据库的学生信息管理程序,程序的功能有:显示所有学生、新增学生、删除学生、修改学生、查找学生(根据学号、姓名、班级、性别、专业、学院等),程序采用命令行方式。
// 2、请编程实现把从数据库中查询出的学生信息记录集(ResultSet)中的记录转换为学生对象。
public class MySqlDAO {
public static Connection getConnection() throws Exception {
String driverName = "com.mysql.cj.jdbc.Driver"; //驱动名称
String url = "jdbc:mysql://localhost:3306/student"; //连接字符串
String username = "root"; //用户名
String ps = ""; //密码
Class.forName(driverName); //加载数据库的驱动,驱动程序自动调用DriverManger中方法将自身注册到管理器中
return DriverManager.getConnection(url, username, password);
}
public static Statement getStatement() throws Exception {
return getConnection().createStatement();
}
public static PreparedStatement preparedStatement(String sql) throws Exception {
return getConnection().prepareStatement(sql);
}
public static void connectionClose() throws Exception {
getConnection().close();
}
}
学生类:
public class Student {
private int Id; //学号
private String Name; //姓名
private String Gender; //性别
private String college; //学院
private String Major; //专业
private int Clazz; //班级
public Student() {
}
public Student(int id, String name, String gender, String college, String major, int Clazz) {
this.Id = id;
this.Name = name;
this.Gender = gender;
this.college = college;
this.Major = major;
this.Clazz = Clazz;
}
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 String getGender() {
return Gender;
}
public void setGender(String gender) {
if (gender.equals("男") || gender.equals("女")) {
this.Gender = gender;
} else {
try {
throw new IllegalAccessException("性别只能为男或女");
} catch (IllegalAccessException E) {
E.printStackTrace();
}
}
}
public String getCollege() {
return college;
}
public void setCollege(String college) {
this.college = college;
}
public String getMajor() {
return Major;
}
public void setMajor(String major) {
this.Major = major;
}
public int getClazz() {
return Clazz;
}
public void setClass(int Clazz) {
this.Clazz = Clazz;
}
}
利用JDBC实现学生管理系统:实现对学生的增删改查的操作
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import static homework3.MySqlDAO.connectionClose;
public class StudentManagementSystem {
static Scanner input = new Scanner(System.in);
static ResultSet rs = null;
public static void main(String[] args) throws Exception {
startSystem();
}
public static void startSystem() throws Exception {
while (true) {
int choice;
System.out.println("学生管理系统");
System.out.println("请选择所需功能");
System.out.println("1.创建学生信息");
System.out.println("2.删除学生信息");
System.out.println("3.修改学生信息");
System.out.println("4.查询学生信息");
System.out.println("5.退出");
choice = input.nextInt();
if (choice == 1) {
createStudent();
} else if (choice == 2) {
while (true) {
System.out.println("请输入要删除学生的学号(输入-1退出):");
int no = input.nextInt();
if (no == -1)
break;
deleteStudent(no);
}
} else if (choice == 3) {
while (true) {
System.out.println("输入要修改学生的学号,如果学号不存在则创建(输入-1退出)");
int no = input.nextInt();
if (no == -1)
break;
updateStudent(no);
}
} else if (choice == 4) {
int choice1;
while (true) {
System.out.println("请输入查询的方式");
System.out.println("1.通过学号查询");
System.out.println("2.通过姓名查询");
System.out.println("3.通过性别查询");
System.out.println("4.通过学院查询");
System.out.println("5.通过专业查询");
System.out.println("6.通过班级查询");
System.out.println("7.退出");
choice1 = input.nextInt();
if (choice1 == 1) {
System.out.println("请输入学号:");
int xuehao = input.nextInt();
selectStudentById(xuehao);
} else if (choice1 == 2) {
System.out.println("请输姓名:");
String name1 = input.next();
selectStudentByName(name1);
} else if (choice1 == 3) {
System.out.println("请输入性别:");
String gender1 = input.next();
selectStudentByGender(gender1);
} else if (choice1 == 4) {
System.out.println("请输入学院:");
String college1 = input.next();
selectStudentByCollege(college1);
} else if (choice1 == 5) {
System.out.println("请输入专业:");
String major1 = input.next();
selectStudentByMajor(major1);
} else if (choice1 == 6) {
System.out.println("请输入班级:");
int class1 = input.nextInt();
selectStudentByClass(class1);
} else {
break;
}
}
} else {
break;
}
}
}
public static void createStudent() throws Exception {
System.out.println("请输入你想创建的学生的信息(输入-1退出):");
int no, clazz;
String name, gender, college, major;
while (true) {
System.out.println("学号:");
no = input.nextInt();
if (no == -1)
break;
System.out.println("姓名:");
name = input.next();
if (name.equals("-1"))
break;
System.out.println("性别:");
gender = input.next();
if (gender.equals("-1"))
break;
System.out.println("学院:");
college = input.next();
if (college.equals("-1"))
break;
System.out.println("专业:");
major = input.next();
if (major.equals("-1"))
break;
System.out.println("班级:");
clazz = input.nextInt();
if (clazz == -1)
break;
Student newStudent = new Student(no, name, gender, college, major, clazz);
insertStudent(newStudent);
}
}
public static boolean tableNameExist(String tableName) throws Exception {
String sql = "select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA='student' and TABLE_NAME='" + tableName + "'";
PreparedStatement ps = MySqlDAO.preparedStatement(sql);
ps.execute();
ResultSet rs = ps.executeQuery();
rs.close();
ps.close();
connectionClose();
return rs.next();
}
public static void createTable(String tableName) throws Exception {
String sql = "create table " + tableName + "(No int primary key, name char(20),gender char(4),college char(100),major char(100),Class int)";
if (!tableNameExist(tableName)) {
PreparedStatement ps = MySqlDAO.preparedStatement(sql);
ps.execute();
ps.close();
} else {
try {
throw new Exception("该表已经存在");
} catch (Exception E) {
E.printStackTrace();
}
}
}
public static void insertStudent(Student student) throws Exception {
String sql = "insert into student values(?,?,?,?,?,?)";
PreparedStatement ps = MySqlDAO.preparedStatement(sql);
ps.setInt(1, student.getId());
ps.setString(2, student.getName());
ps.setString(3, student.getGender());
ps.setString(4, student.getCollege());
ps.setString(5, student.getMajor());
ps.setInt(6, student.getClazz());
ps.execute();
ps.close();
connectionClose();
}
public static void deleteStudent(int no) throws Exception {
String sql = "delete from student where No=?";
PreparedStatement ps = MySqlDAO.preparedStatement(sql);
ps.setInt(1, no);
ps.execute();
ps.close();
connectionClose();
}
public static void updateStudent(int no) throws Exception {
int clazz;
String name, gender, college, major;
deleteStudent(no);
System.out.println("姓名:");
name = input.next();
System.out.println("性别:");
gender = input.next();
System.out.println("学院:");
college = input.next();
System.out.println("专业:");
major = input.next();
System.out.println("班级:");
clazz = input.nextInt();
Student newStudent = new Student(no, name, gender, college, major, clazz);
insertStudent(newStudent);
}
public static void printInformation(ResultSet rs) throws SQLException {
while (rs.next()) {
System.out.println("id: " + rs.getInt("no"));
System.out.println("name: " + rs.getString("name"));
System.out.println("gender: " + rs.getString("gender"));
System.out.println("college: " + rs.getString("college"));
System.out.println("major: " + rs.getString("major"));
System.out.println("class: " + rs.getInt("class"));
System.out.println();
}
}
public static void executeToRs(PreparedStatement ps) throws Exception {
rs = ps.executeQuery();
ps.close();
connectionClose();
}
public static void selectStudentById(int id) throws Exception {
String sql = "select * from student where no = " + id;
PreparedStatement ps = MySqlDAO.preparedStatement(sql);
executeToRs(ps);
printInformation(rs);
ps.close();
connectionClose();
}
public static void selectStudentByName(String name) throws Exception {
String sql = "select * from student where name = " + name;
PreparedStatement ps = MySqlDAO.preparedStatement(sql);
executeToRs(ps);
printInformation(rs);
ps.close();
connectionClose();
}
public static void selectStudentByGender(String gender) throws Exception {
String sql = "select * from student where gender = " + gender;
PreparedStatement ps = MySqlDAO.preparedStatement(sql);
executeToRs(ps);
printInformation(rs);
ps.close();
connectionClose();
}
public static void selectStudentByCollege(String college) throws Exception {
String sql = "select * from student where college = " + college;
PreparedStatement ps = MySqlDAO.preparedStatement(sql);
executeToRs(ps);
printInformation(rs);
ps.close();
connectionClose();
}
public static void selectStudentByMajor(String major) throws Exception {
String sql = "select * from student where major = " + major;
PreparedStatement ps = MySqlDAO.preparedStatement(sql);
executeToRs(ps);
printInformation(rs);
ps.close();
connectionClose();
}
public static void selectStudentByClass(int clazz) throws Exception {
String sql = "select * from student where class = " + clazz;
PreparedStatement ps = MySqlDAO.preparedStatement(sql);
executeToRs(ps);
printInformation(rs);
ps.close();
connectionClose();
}
public static void rsToObject(ResultSet rs) throws SQLException {
List students = new ArrayList<>();
while (rs.next()) {
int no = rs.getInt("no");
String name = rs.getString("name");
String gender = rs.getString("gender");
String college = rs.getString("college");
String major = rs.getString("major");
int clazz = rs.getInt("class");
students.add(new Student(no, name, gender, college, major, clazz));
}
}
}
JDBC的全称指的是Java数据库连接,指的是Java数据库数据库连接,是一种标准的Java应用编程接口。是一套用于执行SQL语句的Java API。应用程序可以通过这一套API连接到关系数据库,并且可以使用SQL语句来完成对数据库之中的数据增删改查等功能。
常用接口:
ResultSet接口
ResultSet提供检索不同类型字段的方法,常用的有:
-
- getDate(int index)、getDate(String columnName):获得在数据库里是Date类型的数据。
- getObject(int index)、getObject(String columnName):获取在数据库里任意类型的数据
- getString(int index)、getString(String columnName):获得在数据库里是varchar、char等类型的数据对象。
- getFloat(int index)、getFloat(String columnName):获得在数据库里是Float类型的数据对象。
- getBoolean(int index)、getBoolean(String columnName):获得在数据库里是Boolean类型的数据。
ResultSet还提供了对结果集进行滚动的方法:
-
- absolute(int row):移动到指定行
- afterLast() :移动到resultSet的最后面。
- next():移动到下一行
- Previous():移动到前一行
- beforeFirst():移动resultSet的最前面。
使用后依次关闭对象及连接:ResultSet → Statement → Connection
1.Driver接口
Driver接口由数据库厂家提供,如果我们需要连接数据库,必须先装载特定厂商的数据库驱动程序。如:
装载MySql驱动:Class.forName("com.mysql.jdbc.Driver");
装载Oracle驱动:Class.forName("oracle.jdbc.driver.OracleDriver");
2.Connection接口
Connection与特定数据库的连接(会话),在连接上下文中执行sql语句并返回结果。DriverManager.getConnection(url, user, password)方法建立在JDBC URL中定义的数据库Connection连接上。
连接MySql数据库:Connection conn = DriverManager.getConnection("jdbc:mysql://host:port/database", "user", "password");
-
- setAutoCommit(boolean autoCommit):设置事务是否自动提交。
- rollback() :在此链接上回滚事务。createStatement():创建向数据库发送sql的statement对象。
- prepareStatement(sql) :创建向数据库发送预编译sql的PrepareSatement对象。
- prepareCall(sql):创建执行存储过程的callableStatement对象。
- commit() :在链接上提交事务。
3.Statement接口
用于执行静态SQL语句并返回它所生成结果的对象。
三种Statement类:
-
- CallableStatement:继承自PreparedStatement接口,由方法prepareCall创建,用于调用存储过程。
- Statement:由createStatement创建,用于发送简单的SQL语句(不带参数)。
- PreparedStatement :继承自Statement接口,由preparedStatement创建,用于发送含有一个或多个参数的SQL语句。PreparedStatement对象比Statement对象的效率更高,并且可以防止SQL注入,所以我们一般都使用PreparedStatement。
常用Statement方法:
-
- executeBatch():向数据库发送一批sql语句执行。
- execute(String sql):运行语句,返回是否有结果集
- addBatch(String sql) :把多条sql语句放到一个批处理中。
- executeQuery(String sql):运行select语句,返回ResultSet结果集。
- executeUpdate(String sql):运行insert/update/delete操作,返回更新的行数。
4.ResultSet接口
ResultSet提供检索不同类型字段的方法,常用的有:
-
- getObject(int index)、getObject(String columnName):获取在数据库里任意类型的数据。
- getString(int index)、getString(String columnName):获得在数据库里是varchar、char等类型的数据对象。
- getBoolean(int index)、getBoolean(String columnName):获得在数据库里是Boolean类型的数据。
- getFloat(int index)、getFloat(String columnName):获得在数据库里是Float类型的数据对象。
- getDate(int index)、getDate(String columnName):获得在数据库里是Date类型的数据。
ResultSet还提供了对结果集进行滚动的方法:
-
- next():移动到下一行
- Previous():移动到前一行
- absolute(int row):移动到指定行
- beforeFirst():移动resultSet的最前面。
- afterLast() :移动到resultSet的最后面。
使用后依次关闭对象及连接:ResultSet → Statement → Connection
使用JDBC的步骤:注册驱动、建立连接、创建执行SQL语句的statement、处理执行结果、释放资源。
暑期编程PK赛 得CSDN机械键盘等精美礼品!


