给我一个基于java的简单学生宿舍管理系统,要用到jdbc和mysql,并且实在控制台运行
时间: 2024-03-26 09:38:34 浏览: 13
好的,以下是一个简单的学生宿舍管理系统的Java代码,使用JDBC连接MySQL数据库,在控制台运行:
```
import java.sql.*;
public class DormitoryManagementSystem {
// 数据库连接信息
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/dormitory";
static final String USER = "root";
static final String PASSWORD = "123456";
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, PASSWORD);
// 执行查询
System.out.println("创建学生表...");
stmt = conn.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS student (id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255), room VARCHAR(255), PRIMARY KEY (id))";
stmt.executeUpdate(sql);
// 添加学生信息
System.out.println("添加学生信息...");
sql = "INSERT INTO student (name, room) VALUES ('张三', '101')";
stmt.executeUpdate(sql);
sql = "INSERT INTO student (name, room) VALUES ('李四', '102')";
stmt.executeUpdate(sql);
// 查询学生信息
System.out.println("查询学生信息...");
sql = "SELECT id, name, room FROM student";
ResultSet rs = stmt.executeQuery(sql);
// 输出学生信息
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String room = rs.getString("room");
System.out.print("ID: " + id);
System.out.print(", 姓名: " + name);
System.out.println(", 房间号: " + room);
}
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("程序结束。");
}
}
}
```
这个程序会创建一个名为`dormitory`的数据库,并在其中创建一个名为`student`的表,然后添加几个学生信息,最后查询并输出所有学生信息。你可以根据需要修改代码来适应自己的需求。