Statement接口使用
时间: 2024-05-03 10:16:37 浏览: 14
Statement 接口是 Java JDBC API 中的一个核心接口,用于执行 SQL 语句并返回结果。它定义了执行 SQL 语句的方法,以及获取执行结果的方法。
使用 Statement 接口的步骤如下:
1. 创建 Statement 对象:通过 Connection 对象的 createStatement() 方法创建 Statement 对象。
2. 执行 SQL 语句:通过 Statement 对象的 execute() 或 executeUpdate() 方法执行 SQL 语句。
3. 处理执行结果:通过 Statement 对象的 getResultSet() 或 getUpdateCount() 方法获取执行结果。
4. 关闭 Statement 对象:通过 Statement 对象的 close() 方法关闭 Statement 对象。
具体使用方法可以参考以下示例代码:
```java
try {
// 创建 Connection 对象
Connection conn = DriverManager.getConnection(url, username, password);
// 创建 Statement 对象
Statement stmt = conn.createStatement();
// 执行 SQL 语句
String sql = "SELECT * FROM users";
ResultSet rs = stmt.executeQuery(sql);
// 处理执行结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("id=" + id + ", name=" + name + ", age=" + age);
}
// 关闭 ResultSet 和 Statement 对象
rs.close();
stmt.close();
// 关闭 Connection 对象
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
```