【发布时间】: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