java - 调用两个数据库服务器的最佳方法

标签 java mysql select

我想同时调用不同数据库的两个表。数据库A的表包含用户id,数据库B的表包含用户位置和用户id,所以我想连接这两个表并获取与user_id对应的位置.数据库A和B位于两个不同的服务器中。那么我怎样才能加入这两个表呢?如果无法加入,是否有任何有效的方法可以做到这一点。请帮忙。我正在尝试使用 java、mysql 来做到这一点。

 ps = con.prepareStatement("SELECT user_id FROM A.users");
 rs = ps.executeQuery();
 while(rs.next())
    {
    //call select statement for database B to get the location for each user id             

    }

请建议一种有效的方法来做到这一点

Id  User_id
===========
1   44
2   23

User_id     location
====================
44          india
23          us

最佳答案

假设user_id是一个long

PreparedStatement psUserLocation = conB.prepareStatement("SELECT location FROM B.users WHERE user_id = ?");
while(rs.next()) {
    //call select statement for database B to get the location for each user id
    long userId = rs.getLong(user_id);
    psUserLocation.setLong(1, userId)
    ResultSet userLocation = ps.executeQuery();
    // Do whatever with the location(s)
}

编辑:对所有用户进行一次查询,而不是对每个用户进行一次查询:

private final static String QUERY = "SELECT user_id, location FROM B.users WHERE user_id IN (%a)";

StringBuilder userList = new StringBuilder();
while(rs.next()) {
    long userId = rs.getLong(user_id);
    userList.append(userId);
    if (!rs.isLast()) {
        userList.append(",");
    }
}

String usersLocationQuery = QUERY.replaceAll("%a", userList.toString());
PreparedStatement psUsersLocation = conB.prepareStatement(usersLocationQuery);
ResultSet usersLocation = psUsersLocation.executeQuery();
// Do whatever with the locations

请记住,这可能会失败/工作错误,因为大多数数据库对 SQL IN 子句可以包含的项目数都有限制。此外,第二种方法可能允许对 %a 替换进行 SQL 注入(inject)。

关于java - 调用两个数据库服务器的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14019618/

相关文章:

java - Spring中的数据库连接管理

php - 插入时 SQL 语法错误

mysql - 删除总计数的百分比

sql - 甲骨文 SQL : Updating a column with SUM query of another table

java - HSQL 和 DBUnit - 给定架构 'SA' 不存在

java - 错误 : Could not write JSON: Class java. util.ArrayList 不是映射的子类型 - Spring 应用程序中序列化为 JSON

java - 使用 spring mvc 在单击按钮时在表上添加行并将添加的行绑定(bind)到 modelAttribute

mysql - 在类似mysql的查询中使用used关键字获取匹配结果

php - 我可以在 select 语句中使用两个Where吗

php - 使用 join (codeigniter) 从单个字段中检索并打印逗号分隔符后的值