【问题标题】:How can i modify a sql connection string at runtime?如何在运行时修改 sql 连接字符串?
【发布时间】:2023-02-23 16:59:56
【问题描述】:

我查询数据库如下:

string connString = "Data Source=ServerName;Initial Catalog=AdventureWorks;User 
     id=UserName;Password=Secret;";    
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand("select * from Orders", connString);
conn.Open();

问题是服务器可能需要设置 TrustServerCertificate 和 Encrypt

因此,如果我运行上面的代码,它将因错误而失败

  SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. 
  (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)]

但如果我有 connString 作为

"Data Source=ServerName;Initial Catalog=AdventureWorks;User 
 id=UserName;Password=Secret;Encrypt=true;TrustServerCertificate=true");

然后它将毫无问题地连接并且选择将运行。

所以我可能需要即时更改连接字符串 有没有一种聪明的方法可以修改上面的代码,以检查是否返回错误,然后使用修改后的新连接字符串重试选择?

【问题讨论】:

  • 因此,您事先不知道要连接的服务器是否需要 TrustServerCertificate?
  • 那天晚上我不知道,但如果我收到上述异常错误,我需要调整连接字符串并重试

标签: c# sqlconnection


【解决方案1】:

将您的代码放入 try 块并捕获 SqlException。然后,更改您的 SqlCommand 连接字符串并重试连接。

    string connString = "Data Source=ServerName;Initial Catalog=AdventureWorks;Userid=UserName;Password=Secret;";    
    SqlConnection conn = new SqlConnection();
    SqlCommand cmd = new SqlCommand("select * from Orders", connString);
    try
    {
       conn.Open();
    }
    catch (SqlException ex)
    {
       cmd.ConnectionString = "Data Source=ServerName;Initial Catalog=AdventureWorks;Userid=UserName;Password=Secret;Encrypt=true;TrustServerCertificate=true";
       conn.Open()
    }
    catch (Exception ex)
    {
       Console.Write($"Error: {ex.Message}")
    }

【讨论】:

  • 这实际上是如何重新运行 select cmd 的,它只是更改了连接字符串?
  • 尝试连接是否会更好,如果它获得证书异常,请更改 strig 并重新运行,因为当它通过修改重新运行时,它会起作用吗?
  • 这就是它正在做的。
  • 啊是的对不起,你是对的,谢谢
猜你喜欢
  • 1970-01-01
  • 2010-11-04
  • 1970-01-01
  • 2017-11-17
  • 2019-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多