how can i retrieve data from multiple databases in a single query?

Rik  picture Rik · Jun 11, 2014 · Viewed 11.3k times · Source

if i have multiple database with same Tables and Columns how can i retrieve Data from those Databases using single Query in Java. Done this for single Database, i am newbie in java, please suggest.

public class MultipleDBTest{
   public void dbConnect(String db_connect_string, String db_userid, String db_password){
     try{
       Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
       Connection conn = DriverManager.getConnection(db_connect_string, db_userid, db_password);
       System.out.println("connected");
       Statement statement = conn.createStatement();
       String queryString = "select <Col1>, <Col2> from <Table>";
       ResultSet rs = statement.executeQuery(queryString);
        while(rs.next()){
          System.out.println(rs.getString(1) + " | " + rs.getString(2));
        }
      }
      catch(Exception e){
        e.printStackTrace();
      }
  }

  public static void main(String[] args){
    ConnectMSSQLServer connServer = new ConnectMSSQLServer();
    connServer.dbConnect("jdbc:sqlserver://localhost;databaseName=<Database1>","<Username>","<Password>");
  }
}

Answer

JotaBe picture JotaBe · Jun 11, 2014

The easiest way to get data from multiple servers is linking them, querying the data from each table using the fully qualified table name, i.e. Server.Database.Schema.Table, and make the union of all.

Yo can only specify the desired server in the fully qualified name, Server, if you link the other servers to the server where you're making the query.

You'd end up with something like this

select * from Server1.Database1.dbo.Table
  union
select * from Server2.Database2.dbo.Table
  union
select * from Server3.Database2.dbo.Table

Please, see this article to understand what are linked servers and how you set them up: Linked Servers (Database Engine).