当我尝试连接SQL Server时,我正在使用下面提到的代码。我正在为用户'domain \ username'登录失败。我已经检查过SQL Server&amp ;;中具有sysadmin权限的用户我正在使用SQL Server Express版。
我用于此“初始目录=员工;服务器= serverName”
的连接字符串 public static bool connectSqlClient(string connecton)
{
bool isConnect = false;
try
{
string username = @"domain\username";
string initString = "abcpassowrd";
// Instantiate the secure string.
SecureString testString = new SecureString();
// Use the AppendChar method to add each char value to the secure string.
foreach (char ch in initString)
testString.AppendChar(ch);
testString.MakeReadOnly();
SqlCredential cred = new SqlCredential(username, testString);
SqlConnection conn = new SqlConnection(connecton, cred);
conn.Open();
isConnect = true;
}
catch (Exception)
{
throw;
}
return isConnect;
}
如果我错过了什么,请告诉我。
答案 0 :(得分:2)
通常,当您向Sql Server添加登录时,有2种模式。
Sql Server身份验证("旧学校"用户名和密送方案)
和
" Windows身份验证"。 您可以在网络上找到用户(域\用户名)并添加登录信息。 这个场景不需要设置/发送密码。
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
这是典型的" Windows身份验证"连接字符串。您没有设置用户名/密码,因为IIDentity已被"拾起"来自谁/登录的任何内容或应用程序正在运行的凭据。
我认为您想要使用Windows身份验证(因为您提到'域/用户名')....但您正在设置pwd,就好像您使用的是Sql-Server-验证。因此"混合" 2个型号。
正如mkross提到的那样,仅仅因为你添加了LOGIN,你仍然需要"链接到"数据库本身。如果您转到安全/登录/(属性)并转到"用户映射"选择,你可以" Map"到数据库,并选择像" db_datareader"这样的role_membership。作为一个低权利角色。
APPEND:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcredential%28v=vs.110%29.aspx
SqlCredential provides a more secure way to specify the password for a login attempt using SQL Server Authentication.
SqlCredential is comprised of a user id and a password that will be used for SQL Server Authentication.
所以,是的,这是针对Sql-Server-Authentication的。不是Windows身份验证。
你可能只需要string myConnectionString = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;"
答案 1 :(得分:1)
虽然您可能已创建用户,但您是否已将该特定用户添加到实际数据库中?
在我继承了已经创建用户的演示之后,这让我感到很沮丧。当我备份并恢复它时,用户不包括在内,需要重新添加。
在这里,您可以看到文件夹安全,登录作为子文件夹: http://i.stack.imgur.com/oiHrb.png
首先在此处添加用户。
创建登录后,您需要扩展实际的数据库本身并在那里添加登录。
答案 2 :(得分:0)
创建帐户后确保重新启动服务器实例!!
我多次遇到过这个问题。您可以在管理工作室中通过右键单击服务器实例并选择重新启动来执行此操作。
或者您可以通过SQL Server配置管理器执行此操作。除此之外,您的代码看起来还不错。