【问题标题】:ASP.net Connecting to two databases at once?ASP.net 同时连接两个数据库?
【发布时间】:2012-03-07 11:06:29
【问题描述】:

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

这种双重操作可以吗?

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

谢谢。

【问题讨论】:

  • 您在尝试时遇到任何问题吗?
  • 当然可以:使用两个连接对象。你遇到什么麻烦了吗?
  • 不,我没有尝试过,在尝试之前我在谷歌上搜索过,发现它被认为是糟糕的设计/实践,但没有找到确切的原因,所以我想我应该在这里问。实际上我使用的数据库是两个完全不同的数据库,但是第二个数据库也需要客户表(在第一个数据库中)来检查现有的电子邮件地址。此外,我正在根据新电子邮件或现有电子邮件的决定执行非常关键的操作,因为它将决定一封电子邮件是关于销售部门还是关于支持部门,所以如果这种方法有任何问题,那么我就放弃它。

标签: c# asp.net sql database multiple-databases


【解决方案1】:

是的,这是可能的。

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

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

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

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

或者这可以在 SQL 结束时完成,例如:

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

【讨论】:

    【解决方案2】:

    也许这对你有帮助 或发布你的代码

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

    // ...

    【讨论】:

      【解决方案3】:

      这是一个很好的解决方案,但不是正确的答案!无需使用 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
      );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-11
        • 2014-03-06
        • 1970-01-01
        • 2022-07-26
        相关资源
        最近更新 更多