Java图书管理系统怎么连接数据库
时间: 2023-06-27 08:01:23 浏览: 77
要连接Java图书管理系统与数据库,需要使用Java数据库连接(JDBC)API。以下是连接数据库的基本步骤:
1. 导入所需的JDBC库文件。
2. 加载数据库驱动程序。
3. 使用驱动管理器获取数据库连接。
4. 创建一个Statement对象。
5. 执行SQL查询语句或更新语句。
6. 处理结果集。
7. 关闭数据库连接。
以下是一个简单的示例代码,演示了如何连接到MySQL数据库:
```java
import java.sql.*;
public class BookManagementSystem {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root", "password");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM books");
while (rs.next()) {
System.out.println(rs.getString("title") + " by " + rs.getString("author"));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
这个示例代码连接到名为library的MySQL数据库,用户名为root,密码为password,然后执行一条SELECT语句,查询books表中的所有书籍,并打印书名和作者。注意,在使用完连接、语句和结果集之后,要关闭它们以释放资源。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)