javaweb学生信息管理系统用到的核心代码
时间: 2023-07-03 15:23:31 浏览: 137
以下是一个简单的JavaWeb学生信息管理系统的核心代码,包括数据库连接、查询和更新操作:
1. 数据库连接代码:
```
public class DBUtil {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/student";
private static final String USERNAME = "root";
private static final String PASSWORD = "123456";
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName(DRIVER);
Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
return conn;
}
}
```
2. 查询数据库中所有学生信息的代码:
```
public class StudentDao {
public List<Student> getAllStudents() {
List<Student> students = new ArrayList<Student>();
String sql = "select * from student";
try {
Connection conn = DBUtil.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
student.setGender(rs.getString("gender"));
student.setMajor(rs.getString("major"));
students.add(student);
}
rs.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return students;
}
}
```
3. 向数据库中插入学生信息的代码:
```
public class StudentDao {
public boolean addStudent(Student student) {
boolean result = false;
String sql = "insert into student(name, age, gender, major) values(?, ?, ?, ?)";
try {
Connection conn = DBUtil.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, student.getName());
stmt.setInt(2, student.getAge());
stmt.setString(3, student.getGender());
stmt.setString(4, student.getMajor());
int rows = stmt.executeUpdate();
if (rows > 0) {
result = true;
}
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
}
```
阅读全文