如何在C#中的单个连接字符串中访问两个数据库?

时间:2018-11-10 16:46:36

标签: c# database

我需要在VS 2010(c#)中使用相同的Windows窗体访问两个不同的Sql数据库。

using System.Data.SqlClient;

//My Code For Connection of one Database named sms. 

SqlConnection con = new SqlConnection(@"Data 
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\sms.mdf;Integrated 
Security=True;Connect Timeout=30;User Instance=True");

我还希望以相同的形式访问名称为sms2的数据库。

SqlConnection con = new SqlConnection(@"Data 
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\sms2.mdf;Integrated 
Security=True;Connect Timeout=30;User Instance=True");

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您使用两个单独的连接对象:

SqlConnection con1 = new SqlConnection(@"Data 
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\sms.mdf;Integrated 
Security=True;Connect Timeout=30;User Instance=True");

SqlConnection con2 = new SqlConnection(@"Data 
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\sms2.mdf;Integrated 
Security=True;Connect Timeout=30;User Instance=True");