使用jdbc编写图书管理系统
时间: 2023-07-08 16:47:55 浏览: 62
好的,下面是一个简单的使用JDBC连接MySQL数据库并实现图书管理的示例代码:
```java
import java.sql.*;
public class BookManager {
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
public BookManager() {
try {
// 加载JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 建立数据库连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookdb", "root", "password");
// 创建Statement对象
stmt = conn.createStatement();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void addBook(String title, String author, String publisher, int year) {
try {
// 执行SQL语句,插入新书籍
String sql = "INSERT INTO books (title, author, publisher, year) VALUES ('" + title + "', '" + author + "', '" + publisher + "', " + year + ")";
stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateBook(int id, String title, String author, String publisher, int year) {
try {
// 执行SQL语句,更新指定id的书籍信息
String sql = "UPDATE books SET title='" + title + "', author='" + author + "', publisher='" + publisher + "', year=" + year + " WHERE id=" + id;
stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void deleteBook(int id) {
try {
// 执行SQL语句,删除指定id的书籍
String sql = "DELETE FROM books WHERE id=" + id;
stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void listBooks() {
try {
// 执行SQL语句,查询所有书籍信息
String sql = "SELECT * FROM books";
rs = stmt.executeQuery(sql);
// 遍历ResultSet对象,输出查询结果
while (rs.next()) {
int id = rs.getInt("id");
String title = rs.getString("title");
String author = rs.getString("author");
String publisher = rs.getString("publisher");
int year = rs.getInt("year");
System.out.println(id + "\t" + title + "\t" + author + "\t" + publisher + "\t" + year);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void close() {
try {
// 关闭ResultSet、Statement和Connection对象
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
BookManager bm = new BookManager();
bm.addBook("Java编程思想", "Bruce Eckel", "机械工业出版社", 2007);
bm.addBook("Thinking in Java", "Bruce Eckel", "Prentice Hall", 2006);
bm.listBooks();
bm.updateBook(1, "Java编程思想(第4版)", "Bruce Eckel", "机械工业出版社", 2009);
bm.deleteBook(2);
bm.listBooks();
bm.close();
}
}
```
在这个示例代码中,我们使用JDBC连接了一个名为bookdb的MySQL数据库,实现了添加新书籍、更新和删除图书信息以及列出所有书籍的功能。在main方法中,我们演示了如何使用这些方法来管理图书。
需要注意的是,这个示例代码中的SQL语句使用了字符串拼接的方式来构建,这样容易受到SQL注入攻击。在实际的应用中,应该使用PreparedStatement来构建SQL语句,以避免SQL注入攻击。