Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>");
  }
}
like image 974
Rikhi Sahu Avatar asked Oct 31 '22 22:10

Rikhi Sahu


1 Answers

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).

like image 182
JotaBe Avatar answered Nov 09 '22 08:11

JotaBe