1 在数据库中创建一个图书表,包含以下字段(id,书名,价格,出版社,作者) 2 根据条件查询图书记录,并显示 3 可以新增一条记录 4 可以根据id修改一条记录 5 可以根据id删除一条记录使用Java语言实现
时间: 2024-02-14 18:22:09 浏览: 144
基于Java实现的一个用于生成代码、创建或读取数据库表信息的工具包
好的,我明白了。以下是Java语言实现的示例代码:
1. 创建图书表并连接数据库
```java
import java.sql.*;
public class Book {
private static final String URL = "jdbc:mysql://localhost:3306/book_db";
private static final String USER = "root";
private static final String PASSWORD = "password";
private static Connection conn;
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// 连接数据库成功
}
}
```
2. 根据条件查询图书记录并显示
```java
public static void queryBooks(String condition) {
String sql = "SELECT * FROM book WHERE " + condition;
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
double price = rs.getDouble("price");
String publisher = rs.getString("publisher");
String author = rs.getString("author");
System.out.println(id + " " + name + " " + price + " " + publisher + " " + author);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
```
3. 新增一条记录
```java
public static void addBook(String name, double price, String publisher, String author) {
String sql = "INSERT INTO book (name, price, publisher, author) VALUES (?, ?, ?, ?)";
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setDouble(2, price);
pstmt.setString(3, publisher);
pstmt.setString(4, author);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
```
4. 根据id修改一条记录
```java
public static void updateBook(int id, String name, double price, String publisher, String author) {
String sql = "UPDATE book SET name=?, price=?, publisher=?, author=? WHERE id=?";
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setDouble(2, price);
pstmt.setString(3, publisher);
pstmt.setString(4, author);
pstmt.setInt(5, id);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
```
5. 根据id删除一条记录
```java
public static void deleteBook(int id) {
String sql = "DELETE FROM book WHERE id=?";
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
```
阅读全文