21xrx.com
2024-09-19 10:15:13 Thursday
登录
文章检索 我的文章 写文章
用 Java 编写一个简单的购书系统
2023-06-14 16:22:44 深夜i     --     --
Java 购书系统 数据库

我最近编写了一个购书系统,使用 Java 编写。这个系统可以让用户浏览书籍、选择购买书籍,并通过数据库记录订单信息。下面是部分实现代码:


import java.sql.*;

public class Bookstore {

 private Connection conn;

 

 public Bookstore() {

  try {

   String url = "jdbc:mysql://localhost:3306/bookstore";

   String user = "root";

   String password = "password";

   

   conn = DriverManager.getConnection(url, user, password);

  } catch (SQLException e) {

   System.out.println(e.getMessage());

  }

 }

 

 public void listBooks() {

  try {

   Statement stmt = conn.createStatement();

   ResultSet rs = stmt.executeQuery("SELECT * FROM books");

   

   while (rs.next()) {

    System.out.println(rs.getString("title"));

   }

  } catch (SQLException e) {

   System.out.println(e.getMessage());

  }

 }

 

 public void purchaseBook(int bookId, int quantity) {

  try {

   PreparedStatement pstmt = conn.prepareStatement("INSERT INTO orders (book_id, quantity) VALUES (?, ?)");

   pstmt.setInt(1, bookId);

   pstmt.setInt(2, quantity);

   pstmt.executeUpdate();

   

   System.out.println("Order placed successfully!");

  } catch (SQLException e) {

   System.out.println(e.getMessage());

  }

 }

 

 public static void main(String[] args) {

  Bookstore bookstore = new Bookstore();

  bookstore.listBooks();

  bookstore.purchaseBook(1, 2);

 }

}

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复