gpt4 book ai didi

c# - 在 C# 中打开 SqlConnection 时没有异常

转载 作者:太空狗 更新时间:2023-10-29 23:15:13 26 4
gpt4 key购买 nike

我正在制作一个连接到本地 SQL Server 数据库的应用程序,我正在使用以下方法创建连接字符串并测试异常。

public void connect(string user, string password, string server, string database)
{
connectString = "user id=" + user + ";" +
"password=" + password + ";" +
"server=" + server + ";" +
"Trusted_Connection=yes;" +
"database=" + database + ";" +
"connection timeout=5";
myConnection = new SqlConnection(connectString);
try
{
myConnection.Open();
isConnected = true;
}
catch (SqlException)
{
isConnected = false;
}
catch (InvalidOperationException)
{
isConnected = false;
}
}

根据我的研究,如果无法打开连接,应该抛出异常,但如果我传递无意义的凭据或空字符串,则不会抛出异常。如果我传递正确的信息,我就能够连接并使用连接字符串来提取数据。由于连接字符串错误,我稍后在尝试用数据填充 SqlDataAdapter 时遇到异常。

此外,当我调试并检查时,myConnection.State 是打开的,带有无意义的连接字符串。

我对异常捕获应该如何工作的理解有问题吗?当我由于凭据错误而无法连接到数据库时,我认为不应打开 SqlConnection 状态是否正确?

最佳答案

在您的连接字符串中,您有 "Trusted_Connection=yes;",它将使用当前的 Windows 帐户进行身份验证,并将忽略连接字符串中提供的用户名和密码。

参见:Integrated Security -or- Trusted_Connection from SqlConnection.ConnectionString Property

When false, User ID and Password are specified in the connection. When true, the current Windows account credentials are used for authentication. Recognized values are true, false, yes, no, and sspi (strongly recommended), which is equivalent to true.

If User ID and Password are specified and Integrated Security is set to true, the User ID and Password will be ignored and Integrated Security will be used. SqlCredential is a more secure way to specify credentials for a connection that uses SQL Server Authentication (Integrated Security=false).

关于c# - 在 C# 中打开 SqlConnection 时没有异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20806932/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com