定义Book类属性与book表中字段对应;使用JDBC访问book表查询书名中包含Java的书名将查询到的每一本书转换为一个Book类对象存储到集合中。用java代码完成
import java.sql.*; import java.util.ArrayList; import java.util.List;
public class Book { private int id; private String title; private String author; private double price;
public Book(int id, String title, String author, double price) {
this.id = id;
this.title = title;
this.author = author;
this.price = price;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public double getPrice() {
return price;
}
public static void main(String[] args) {
List<Book> books = new ArrayList<>();
String url = "jdbc:mysql://localhost:3306/database_name";
String username = "your_username";
String password = "your_password";
try {
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
String query = "SELECT * FROM book WHERE title LIKE '%Java%'";
ResultSet resultSet = statement.executeQuery(query);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String title = resultSet.getString("title");
String author = resultSet.getString("author");
double price = resultSet.getDouble("price");
Book book = new Book(id, title, author, price);
books.add(book);
}
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
for (Book book : books) {
System.out.println("ID: " + book.getId());
System.out.println("Title: " + book.getTitle());
System.out.println("Author: " + book.getAuthor());
System.out.println("Price: " + book.getPrice());
System.out.println("-----------------------");
}
}
原文地址: https://www.cveoy.top/t/topic/hOos 著作权归作者所有。请勿转载和采集!