在打开连接之前检查登录到SQL Server是否有效

时间:2016-09-27 15:39:06

标签: c# sql sql-server

我正在编写一个C#应用程序,它连接到用户选择的Microsoft SQL Server,使用集成安全性或用户提供的用户名和密码连接到数据库。

目前,如果用户输入了错误的密码或使用的Windows帐户无权访问服务器,则SqlException打开时会抛出SqlConnection

我希望向用户提供不同的反馈,具体取决于是否由于登录失败而引发SqlException,或者由于其他错误而抛出,例如服务器名称不正确。目前找出抛出SqlException的原因的唯一方法是查看消息字符串,这不是一个很好的解决方案。有没有办法在打开SqlConnection之前确定用户名和密码是否正确,或者找出为什么会抛出SqlException

目前,我的连接字符串为Data Source=ServerName\SQLExpress;User=userName;Password=userPassword;Data Source=ServerName\SQLExpress;Integrated Security=true;,具体取决于用户的选择。

打开连接的代码是:

const string ConnectionStringTemplate = "Data Source={0}\\SQLExpress;"; //Basic part of the connection string
const string UserLogInTemplate = "User={0};Password={1}";  //Template for adding user authentication
const string NoAuthString = "Integrated Security=true;"; //If no username/password provided use this

string connectionString;
connectionString = String.Format(ConnectionStringTemplate, serverName);
if (usesAuthentication)
{
    connectionString += String.Format(UserLogInTemplate, userName, password);
}
else
{
    connectionString += NoAuthString;
}
sqlcnn = new SqlConnection(connectionString);

sqlcnn.Open(); //SQLException occurs here if Password incorrect or server name wrong etc.

2 个答案:

答案 0 :(得分:0)

不要让异常发生。

在尝试对其执行任何操作之前验证用户。验证服务器,验证要验证的所有内容。这种方法的问题在于,您永远不会离开验证陷阱,总会出现一些可能出错的问题。我建议你分析哪些问题可能并尝试阻止这些问题,把剩下的问题留给一个通用的SqlException处理程序。

如果你这样做,由于并发性,你的例外发生的可能性仍然很小,但这种情况非常罕见,因此在大多数情况下你不必担心。

关于服务器名称不正确,这种情况极不可能发生。换句话说,如果您的应用程序每天出现问题,<0.001%的情况下它将是服务器名称。

有关更具体的解决方案,请显示一些代码。

答案 1 :(得分:0)

使用SQLExcpetion.Number

抛出的SQLException包含Number属性。

如果登录失败,则Number为18456,如果找不到服务器,则Number为-1。其他错误号与SQL-Server提供的错误号相同,可以在https://technet.microsoft.com/en-us/library/cc645603(v=sql.105).aspx

找到

(感谢Matt)

相关问题