Ian Relado
Ian Relado

Reputation: 31

2 connections to SQL Server

I have a problem, I want to have two connections:

How can I do it in ASP.NET? Can I use connection string?

Thanks

Upvotes: 2

Views: 227

Answers (1)

marc_s
marc_s

Reputation: 754438

In order to connect to two separate SQL Server instances at the same time, you need two connection strings in your web.config (or app.config), and you need to instantiate two SqlConnection objects.

Config:

<connectionStrings>    
    <add name="LocalConnection"
         connectionString="server=.;database=YourDb;Integrated Security=SSPI;" 
         providerName="System.Data.SqlClient" />
    <add name="RemoteConnection"
         connectionString="server=YourRemoteServerName;database=YourRemoteDbName;User ID=SomeUser;Password=Top$ecret" 
         providerName="System.Data.SqlClient" />
</connectionStrings>

And then in your code, you need to instantiate two SqlConnection objects:

// get the connection strings
string conStringLocal = ConfigurationManager.ConnectionStrings["LocalConnection"].ConnectionString;
string conStringRemote = ConfigurationManager.ConnectionStrings["RemoteConnection"].ConnectionString;

// create the two connections
SqlConnection conLocal = new SqlConnection(conStringLocal);
SqlConnection conRemote = new SqlConnection(conStringRemote);

Now, if you need to get something from the local database, use the conLocal connection for your SqlCommand etc. - and for your remote server, use conRemote instead.

Upvotes: 1

Related Questions