用java写一个网吧管理系统,写出源代码,要有链接数据库的功能
时间: 2024-03-08 17:50:08 浏览: 16
好的,下面给出一个简单的网吧管理系统的Java代码,包括数据库链接功能。这里使用MySQL数据库作为例子,你需要在本地安装MySQL数据库,并创建一个名为"cybercafe"的数据库和相应的表格。
```
import java.sql.*;
public class CybercafeSystem {
private static final String URL = "jdbc:mysql://localhost:3306/cybercafe?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
private static final String USER = "root";
private static final String PASSWORD = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 链接数据库
conn = DriverManager.getConnection(URL, USER, PASSWORD);
// 创建查询语句
stmt = conn.createStatement();
String sql = "SELECT * FROM user";
// 执行查询语句
rs = stmt.executeQuery(sql);
// 输出查询结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String password = rs.getString("password");
String gender = rs.getString("gender");
String phone = rs.getString("phone");
System.out.println("ID: " + id + ", Name: " + name + ", Password: " + password + ", Gender: " + gender + ", Phone: " + phone);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
以上代码演示了如何链接数据库,并查询user表格中的所有数据。你可以根据需要修改代码,添加网吧管理系统的其他功能。