学生宿舍调换功能代码Java(连接数据库)
时间: 2024-01-15 20:04:07 浏览: 22
好的,这是一个使用 Java 连接数据库实现学生宿舍调换功能的代码示例:
```java
import java.sql.*;
public class DormitoryChange {
// JDBC 驱动和数据库 URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/dormitory";
// 数据库用户名和密码
static final String USER = "root";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开连接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 执行查询
System.out.println("创建语句对象...");
stmt = conn.createStatement();
String sql = "SELECT * FROM students";
ResultSet rs = stmt.executeQuery(sql);
// 循环遍历结果集
while (rs.next()) {
// 输出数据
System.out.print("学号: " + rs.getInt("id"));
System.out.print(", 姓名: " + rs.getString("name"));
System.out.print(", 宿舍号: " + rs.getString("dormitory_number"));
System.out.println(", 床位号: " + rs.getString("bed_number"));
}
// 关闭结果集、语句对象和连接
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
// 处理 JDBC 错误
se.printStackTrace();
} catch (Exception e) {
// 处理 Class.forName 错误
e.printStackTrace();
} finally {
// 关闭资源
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
} // 什么都不做
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("程序结束。");
}
}
```
上述代码使用 JDBC 驱动连接 MySQL 数据库,执行查询语句,然后遍历结果集输出学生信息。你可以根据自己的需求修改代码,实现学生宿舍调换功能。