java代码连接数据库,写图书管理系统。
时间: 2023-11-30 09:19:18 浏览: 30
好的,以下是一个简单的Java代码连接MySQL数据库并实现基本的图书管理系统:
```java
import java.sql.*;
public class BookManagementSystem {
// 数据库连接信息
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/book_db?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
static final String USER = "root";
static final String PASS = "password";
// 数据库操作对象
static Connection conn = null;
static Statement stmt = null;
public static void main(String[] args) {
try {
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开连接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 执行查询
System.out.println("实例化Statement对象...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, author, price FROM book";
ResultSet rs = stmt.executeQuery(sql);
// 输出结果
while (rs.next()) {
// 通过字段检索
int id = rs.getInt("id");
String name = rs.getString("name");
String author = rs.getString("author");
double price = rs.getDouble("price");
// 输出数据
System.out.print("ID: " + id);
System.out.print(", 书名: " + name);
System.out.print(", 作者: " + author);
System.out.println(", 价格: " + price);
}
// 关闭资源
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
// 处理 JDBC 错误
se.printStackTrace();
} catch (Exception e) {
// 处理 Class.forName 错误
e.printStackTrace();
} finally {
// 关闭资源
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
```
这个代码是一个简单的图书管理系统,它可以从MySQL数据库中读取图书信息并输出。你可以根据自己的需求添加更多的功能,例如添加、修改和删除图书信息。