ASP.net Connecting to two databases at once?

偶尔善良 提交于 2019-12-03 17:06:14

Yes this is possible.

You can either return a value to your asp.net application, and then connect to another database like:

cmdEmailExists SqlCommand = new SqlCommand("SQL HERE...", Conn1);

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

Where Conn1 and Conn2 are 2 different SqlConnection's connecting to 2 different databases.

Or this can be done at SQL end like:

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

may be this helps you or post ur code

 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);

// ...

This is nice solution but not the correct answer! There is no need of using 2 connection string in order to use 2 different databases on the same server (as long as the user have the right permission). We specify the Initial Catalog during the connection, to define where we want to run the query, but if the user have enough permissions to execute the query on other databases, he can do that using the two dots Db..table notation!

This code will work using one connection string!

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
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!