课设目标
1、学习Java连接MySQL数据库的基本方法。
2、掌握Java操作MySQL数据库的基本技能。
3、完成一个简单的Java程序,实现对MySQL数据库的增删改查操作。
环境准备
1、安装Java开发环境(JDK)。
2、安装MySQL数据库。
3、下载并安装MySQL JDBC驱动。
数据库设计
1、创建一个名为student
的数据库。
2、在student
数据库中创建一个名为student_info
的表,包含以下字段:
id(int,主键,自增长)
name(varchar,姓名)
age(int,年龄)
gender(varchar,性别)
class(varchar,班级)
Java代码实现
1、导入相关包:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException;
2、加载并注册MySQL JDBC驱动:
try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); }
3、建立数据库连接:
String url = "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC"; String user = "root"; String password = "your_password"; Connection connection = null;
4、编写增删改查方法:
增加学生信息:
public void addStudent(String name, int age, String gender, String className) { String sql = "INSERT INTO student_info (name, age, gender, class) VALUES (?, ?, ?, ?)"; try { PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, name); preparedStatement.setInt(2, age); preparedStatement.setString(3, gender); preparedStatement.setString(4, className); preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } }
删除学生信息:
public void deleteStudent(int id) { String sql = "DELETE FROM student_info WHERE id = ?"; try { PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, id); preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } }
修改学生信息:
public void updateStudent(int id, String name, int age, String gender, String className) { String sql = "UPDATE student_info SET name = ?, age = ?, gender = ?, class = ? WHERE id = ?"; try { PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, name); preparedStatement.setInt(2, age); preparedStatement.setString(3, gender); preparedStatement.setString(4, className); preparedStatement.setInt(5, id); preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } }
查询学生信息:
public void queryStudent() { String sql = "SELECT * FROM student_info"; try { PreparedStatement preparedStatement = connection.prepareStatement(sql); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); int age = resultSet.getInt("age"); String gender = resultSet.getString("gender"); String className = resultSet.getString("class"); System.out.println("id: " + id + ", name: " + name + ", age: " + age + ", gender: " + gender + ", class: " + className); } } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/640801.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复