Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
by only one ConnectionString

Hi

in ConnectionString we can define db by command "Initial Catalog=MyDB;".
I WANTS TO ACCESS TO 2 DB in SQL Server.
is it posible to access to more than one db of sqlserver
by only one ConnectionString?


Thanks Very Much
Posted

Yes. A single opened connection can access all the databases the current user (the one used to open the connection) has access rights...
C#
SqlConnection oConnection = new SqlConnection(connectionString);
oConnection.Open();
oConnection.ChangeDatabase("mydb1");
// run some query
oConnection.ChangeDatabase("mydb2");
// run some more query
oConnection.Close();
 
Share this answer
 
v2
Comments
Maciej Los 22-Dec-14 15:31pm    
+5!
Kornfeld Eliyahu Peter 22-Dec-14 15:32pm    
Thank you...
Yes, you can use single connection to MS Server to work with more than one database.

To able to achieve that, you need to write query as:
SQL
SELECT <FieldList>
FROM [DatabaseName].[dbo].[TableName]

or
SQL
USE DatabaseName;
SELECT <FieldList>
FROM [TableName]


But, i need to warn you. The best way to fetch data from SQL Server is to use stored procedures.
 
Share this answer
 
Comments
Kornfeld Eliyahu Peter 22-Dec-14 15:29pm    
You also can use the connection object to set the current database - see my answer...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900