Java for循环查询数据库
时间: 2023-10-27 16:06:49 浏览: 55
可以使用Java的for循环结合JDBC API来查询数据库。以下是一个简单的示例代码:
```
import java.sql.*;
public class DatabaseQuery {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Connect to the database
conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "username", "password");
// Create a SQL statement
stmt = conn.createStatement();
// Execute the SQL query
rs = stmt.executeQuery("SELECT * FROM mytable");
// Iterate through the result set
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
// Do something with the data
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close the database resources
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
在上面的示例中,我们通过使用`DriverManager.getConnection()`方法来连接到数据库,然后使用`conn.createStatement()`方法创建一个`Statement`对象。接着,我们使用`stmt.executeQuery()`方法执行SQL查询,并使用`rs.next()`方法遍历查询结果集。在每次迭代中,我们使用`rs.getXXX()`方法从结果集中获取数据,并在控制台上输出。最后,我们使用`finally`块关闭所有的数据库资源。
相关推荐
![](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)
![](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)