数据库系统设计饭店点餐页面设计的java代码
时间: 2023-11-13 09:16:36 浏览: 31
以下是一个简单的Java代码示例,演示如何连接数据库并进行一些基本的操作,例如向数据库中插入数据、查询数据等。该代码示例使用MySQL数据库。
注:该代码示例仅供参考,具体实现可能会因为业务需求而有所不同。
```java
import java.sql.*;
public class RestaurantOrderSystem {
// JDBC驱动名和数据库URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/restaurant_order_system";
// 数据库用户名和密码
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("实例化Statement对象...");
stmt = conn.createStatement();
String sql = "SELECT id, name, price FROM menu";
ResultSet rs = stmt.executeQuery(sql);
// 处理结果集
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
double price = rs.getDouble("price");
// 输出数据
System.out.print("ID: " + id);
System.out.print(", 名称: " + name);
System.out.println(", 价格: " + price);
}
rs.close();
// 执行插入
System.out.println("插入数据...");
sql = "INSERT INTO menu (name, price) VALUES ('烤鸭', 88.0)";
stmt.executeUpdate(sql);
// 再次执行查询,验证插入是否成功
sql = "SELECT id, name, price FROM menu";
rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
double price = rs.getDouble("price");
// 输出数据
System.out.print("ID: " + id);
System.out.print(", 名称: " + name);
System.out.println(", 价格: " + price);
}
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("Goodbye!");
}
}
```
上述代码示例演示了如何连接数据库、执行查询和插入操作,并处理了一些异常。根据具体的业务需求,可以进行相应的修改和扩展。
阅读全文
相关推荐
















