使用JDBC访问数据库的主要流程
时间: 2024-02-25 20:29:14 浏览: 19
使用JDBC访问数据库的主要流程如下:
1. 加载数据库驱动程序:使用 Class.forName() 方法动态加载数据库驱动程序。
2. 建立数据库连接:使用 DriverManager.getConnection() 方法建立与数据库的连接。
3. 创建 SQL 语句:使用 Statement 或 PreparedStatement 对象创建 SQL 查询或更新语句。
4. 执行 SQL 语句:使用 Statement 或 PreparedStatement 对象执行 SQL 查询或更新语句。
5. 处理结果集:使用 ResultSet 对象处理查询结果。
6. 关闭连接:使用 Connection 对象关闭与数据库的连接。
具体代码实现可以参考以下示例:
```java
import java.sql.*;
public class JdbcDemo {
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/test", "root", "123456");
// 创建 SQL 查询语句
String sql = "SELECT * FROM user";
// 创建 Statement 对象
stmt = conn.createStatement();
// 执行 SQL 查询语句
rs = stmt.executeQuery(sql);
// 处理查询结果集
while (rs.next()) {
System.out.println(rs.getInt("id") + "\t" + rs.getString("name") + "\t" + rs.getInt("age"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// 关闭结果集
if (rs != null) rs.close();
// 关闭 Statement 对象
if (stmt != null) stmt.close();
// 关闭数据库连接
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```