java连接数据库的酒店管理系统代码
时间: 2024-06-11 22:02:07 浏览: 13
Java连接数据库可以使用JDBC技术,具体实现步骤如下:
1. 加载数据库驱动
2. 建立数据库连接
3. 创建Statement对象
4. 执行SQL语句并获取结果集
5. 处理结果集
6. 关闭结果集、Statement和连接
以下是一个简单的酒店管理系统代码示例:
```
import java.sql.*;
public class HotelSystem {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载MySQL数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 建立数据库连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hotel", "root", "password");
// 创建Statement对象
stmt = conn.createStatement();
// 查询所有房间信息
rs = stmt.executeQuery("SELECT * FROM room");
// 处理结果集
while (rs.next()) {
int roomId = rs.getInt("room_id");
String roomType = rs.getString("room_type");
int roomPrice = rs.getInt("room_price");
System.out.println("房间编号:" + roomId + ",房间类型:" + roomType + ",房间价格:" + roomPrice);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭结果集、Statement和连接
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
这段代码是一个简单的查询所有房间信息的示例,你可以根据自己的需求进行修改和扩展。