以下是一个使用Java代码遍历ID并在PostgreSQL函数中查询的示例:
import java.sql.*;
public class Main {
public static void main(String[] args) {
String url = "jdbc:postgresql://localhost:5432/db_name";
String user = "username";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
String query = "SELECT * FROM my_function(?)";
PreparedStatement stmt = conn.prepareStatement(query);
// 遍历ID
int[] ids = {1, 2, 3, 4, 5};
for (int id : ids) {
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
// 处理查询结果
int result = rs.getInt("result");
System.out.println("ID: " + id + ", Result: " + result);
}
rs.close();
}
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
在上面的示例中,我们首先建立了与PostgreSQL数据库的连接。然后,我们定义了一个查询字符串,其中我们使用了一个占位符?
来表示传入的ID参数。接下来,我们创建了一个PreparedStatement
对象,用于执行查询。
然后,我们定义了一个整数数组ids
,其中包含要遍历的ID。在for
循环中,我们将每个ID设置为占位符的值,并执行查询。然后,我们使用ResultSet
对象来处理查询结果,并打印每个ID的结果。
最后,我们关闭了ResultSet
和PreparedStatement
对象,并处理了可能出现的异常。
请注意,上述示例中的db_name
应该替换为你的数据库名称,username
和password
应该替换为你的数据库的用户名和密码。另外,你需要根据你的实际情况修改查询字符串和处理查询结果的代码。
下一篇:遍历ID和数组的jQuery循环