应用JDBC访问数据库 创建一个名为Books的数据库,并在其中建立一个名为book_message的表,字段包括书名、作者、出版社、出版时间和价格。编写一个应用程序,用预处理方式在该数据库中实现增加、删除和修改数据以及查
时间: 2024-02-28 13:55:34 浏览: 142
询所有书籍信息的功能。
首先需要安装并配置好JDBC驱动程序,然后编写Java代码来连接数据库。
创建数据库和表的SQL语句如下:
```
CREATE DATABASE Books;
USE Books;
CREATE TABLE book_message (
id INT NOT NULL AUTO_INCREMENT,
book_name VARCHAR(50) NOT NULL,
author VARCHAR(50) NOT NULL,
publisher VARCHAR(50) NOT NULL,
publish_time DATE NOT NULL,
price FLOAT NOT NULL,
PRIMARY KEY (id)
);
```
然后,编写Java代码来实现增删改查功能,示例代码如下:
```java
import java.sql.*;
public class BooksDB {
private static final String URL = "jdbc:mysql://localhost:3306/Books";
private static final String USER = "root";
private static final String PASSWORD = "password";
public static void main(String[] args) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
// 1. 连接数据库
connection = DriverManager.getConnection(URL, USER, PASSWORD);
// 2. 插入数据
String insertSQL = "INSERT INTO book_message (book_name, author, publisher, publish_time, price) VALUES (?, ?, ?, ?, ?)";
statement = connection.prepareStatement(insertSQL);
statement.setString(1, "Java编程思想");
statement.setString(2, "Bruce Eckel");
statement.setString(3, "机械工业出版社");
statement.setDate(4, Date.valueOf("2006-06-01"));
statement.setFloat(5, 89.00f);
statement.executeUpdate();
// 3. 删除数据
String deleteSQL = "DELETE FROM book_message WHERE book_name = ?";
statement = connection.prepareStatement(deleteSQL);
statement.setString(1, "Java编程思想");
statement.executeUpdate();
// 4. 修改数据
String updateSQL = "UPDATE book_message SET price = ? WHERE book_name = ?";
statement = connection.prepareStatement(updateSQL);
statement.setFloat(1, 99.00f);
statement.setString(2, "Head First Java");
statement.executeUpdate();
// 5. 查询数据
String selectSQL = "SELECT * FROM book_message";
statement = connection.prepareStatement(selectSQL);
resultSet = statement.executeQuery();
while (resultSet.next()) {
System.out.println(resultSet.getInt("id") + "\t"
+ resultSet.getString("book_name") + "\t"
+ resultSet.getString("author") + "\t"
+ resultSet.getString("publisher") + "\t"
+ resultSet.getDate("publish_time") + "\t"
+ resultSet.getFloat("price"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 6. 关闭资源
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
这段代码使用了PreparedStatement来执行SQL语句,可以避免SQL注入攻击。同时,使用try-with-resources语句来自动关闭资源。
阅读全文