我想同时调用不同数据库的两个表。数据库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/