JAVA学生信息管理系统GUI界面连接MYSQL代码
时间: 2023-09-10 20:06:52 浏览: 94
学生信息管理系统JAVA GUI +MYSQL
5星 · 资源好评率100%
以下是一个简单的Java学生信息管理系统GUI界面连接MySQL数据库的代码示例:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
public class StudentDAO {
private static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/studentdb";
private static final String USERNAME = "root";
private static final String PASSWORD = "password";
public static Connection getConnection() throws SQLException {
try {
Class.forName(DRIVER_CLASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
public static List<Student> getAllStudents() {
List<Student> students = new ArrayList<Student>();
try {
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM student");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Student s = new Student(rs.getInt("id"), rs.getString("name"), rs.getInt("age"),
rs.getString("gender"), rs.getString("major"));
students.add(s);
}
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return students;
}
public static void addStudent(Student s) {
try {
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement("INSERT INTO student (name, age, gender, major) VALUES (?, ?, ?, ?)");
ps.setString(1, s.getName());
ps.setInt(2, s.getAge());
ps.setString(3, s.getGender());
ps.setString(4, s.getMajor());
ps.executeUpdate();
ps.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void updateStudent(Student s) {
try {
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement("UPDATE student SET name = ?, age = ?, gender = ?, major = ? WHERE id = ?");
ps.setString(1, s.getName());
ps.setInt(2, s.getAge());
ps.setString(3, s.getGender());
ps.setString(4, s.getMajor());
ps.setInt(5, s.getId());
ps.executeUpdate();
ps.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void deleteStudent(Student s) {
try {
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement("DELETE FROM student WHERE id = ?");
ps.setInt(1, s.getId());
ps.executeUpdate();
ps.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
这个示例代码中,我们定义了一个 `StudentDAO` 类,其中包含了对 MySQL 数据库的连接、查询、插入、更新和删除操作。在这个类中,我们使用了 `PreparedStatement` 对象来执行 SQL 命令,这样可以避免 SQL 注入攻击。同时,我们还定义了一个 `Student` 类,表示一个学生信息。在 `getAllStudents()` 方法中,我们使用了 `ResultSet` 对象来获取查询结果,并将结果封装成 `Student` 对象的集合返回。在其他的方法中,我们使用了 `PreparedStatement` 对象来执行对数据库的增、删、改操作。
阅读全文