给我写一个图书管理系统用java和mysql
时间: 2024-03-05 16:48:46 浏览: 74
好的,以下是一个简单的图书管理系统的Java代码和MySQL数据库表结构设计。
Java代码:
```
import java.sql.*;
import java.util.Scanner;
public class BookManagementSystem {
private static final String DB_URL = "jdbc:mysql://localhost:3306/bookstore";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 连接数据库
conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
// 创建表
stmt = conn.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS books (" +
"id INT(11) NOT NULL AUTO_INCREMENT," +
"title VARCHAR(255) NOT NULL," +
"author VARCHAR(255) NOT NULL," +
"genre VARCHAR(255) NOT NULL," +
"price DOUBLE NOT NULL," +
"PRIMARY KEY (id)" +
")";
stmt.executeUpdate(sql);
// 添加图书
Scanner input = new Scanner(System.in);
System.out.print("请输入书名:");
String title = input.nextLine();
System.out.print("请输入作者:");
String author = input.nextLine();
System.out.print("请输入分类:");
String genre = input.nextLine();
System.out.print("请输入价格:");
double price = input.nextDouble();
sql = "INSERT INTO books (title, author, genre, price) VALUES ('" +
title + "', '" + author + "', '" + genre + "', " + price + ")";
stmt.executeUpdate(sql);
// 显示所有图书
sql = "SELECT * FROM books";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
title = rs.getString("title");
author = rs.getString("author");
genre = rs.getString("genre");
price = rs.getDouble("price");
System.out.print("ID: " + id);
System.out.print(", 标题: " + title);
System.out.print(", 作者: " + author);
System.out.print(", 分类: " + genre);
System.out.println(", 价格: " + price);
}
// 关闭连接
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
MySQL数据库表结构设计:
```
CREATE TABLE IF NOT EXISTS books (
id INT(11) NOT NULL AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
author VARCHAR(255) NOT NULL,
genre VARCHAR(255) NOT NULL,
price DOUBLE NOT NULL,
PRIMARY KEY (id)
);
```
该系统只实现了添加和显示图书的功能,您可以根据需要进行扩展。同时,请注意在实际项目中,应该使用PreparedStatement代替Statement来避免SQL注入攻击,也应该对输入的数据进行合法性验证。
阅读全文