how can i access multiple databases in dataaccess layer to c# .net applications?

Recommended Answers

All 2 Replies

That depends on how your DAL is implemented but you can merely switch out the connection string which will connect you to another database.

This queries two database:

private void simpleButton1_Click(object sender, EventArgs e)
    {
      const string query = "Select * from sysobjects";
      string connStr1 = BuildSqlNativeConnStr("apex2006sql", "Leather");
      string connStr2 = BuildSqlNativeConnStr("apex2006sql", "master");
      DataTable dt1 = QueryDataTable(connStr1, query);
      DataTable dt2 = QueryDataTable(connStr2, query);
      Debugger.Break();
    }
    private static DataTable QueryDataTable(string ConnectionString, string Query)
    {
      DataTable result;
      using (SqlConnection conn = new SqlConnection(ConnectionString))
      {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand(Query, conn))
        {
          SqlDataReader dr = cmd.ExecuteReader();
          result = new DataTable();
          result.Load(dr);
        }
      }
      return result;
    }
    public static string BuildSqlNativeConnStr(string server, string database)
    {
      return string.Format("Data Source={0};Initial Catalog={1};Integrated Security=True;", server, database);
    }

In DAL, you can use multiple connection strings dealing with more than one databases. Can use more than one connection, command, etc objects. I have already dealt with 1 MS ACCESS and 2 MYSQL databases in a single class of DAL logic.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.