ASP.net一次连接两个数据库?

可能同时连接两个SQL数据库吗? 我的意思是从一个数据库我正在阅读记录并将它们与一些数据(如电子邮件地址)进行比较,并根据数据库中是否存在该电子邮件地址的决定我将新记录存储在另一个数据库中。

这种双重操作可能吗?

我使用C#.net的SqlConnection和SqlCommand语句连接数据库

谢谢。

是的,这是可能的。

您可以将值返回到asp.net应用程序,然后连接到另一个数据库,如:

cmdEmailExists SqlCommand = new SqlCommand("SQL HERE...", Conn1); if (((int)cmdEmailExists.ExecuteScalar())>0){ cmdInsert SqlCommand = new SqlCommand("SQL INSERT HERE...", Conn2) cmdInsert.ExecuteNonQuery(); } 

其中Conn1Conn2是2个不同的SqlConnection连接到2个不同的数据库。

或者这可以在SQL端完成,如:

 IF EXISTS(SELECT Email FROM [Database1].dbo.tbl) BEGIN INSERT INTO [Database2].dbo.tbl .......... END 

可能这会帮助您或发布您的代码

  SqlConnection con1 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["con1"].ConnectionString); SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["con2"].ConnectionString); SqlCommand cmd = new SqlCommand("select * from table1", con1); SqlDataReader dr; con1.Open(); dr = cmd.ExecuteReader(CommandBehavior.SingleResult); while (dr.Read()) { // .... }dr.Close() //your condition then fire insert commnd with connection con2 SqlCommand insertcmd = new SqlCommand("insert into table2", con2); SqlDataAdapter dap = new SqlDataAdapter(insertcmd); 

// …

这是一个很好的解决方案,但不是正确答案! 不需要使用2个连接字符串就可以在同一台服务器上使用2个不同的数据库(只要用户拥有正确的权限)。 我们在连接期间指定初始目录,以定义我们想要运行查询的位置,但如果用户有足够的权限在其他数据库上执行查询,他可以使用两个点Db..table表示法来做到这一点

此代码将使用一个连接字符串!

 SqlConnection con = new SqlConnection(@"Use-connection-string-here"); SqlCommand cmd = new SqlCommand( "select * from Table1 t1 left join Database2..Table2 t2 on t1.id = t2.id", con );