连接到 SQL 数据库时出错:无法打开登录请求的数据库 "Students.mdf"。登录失败

Error when connecting to a SQL database: Cannot open database "Students.mdf" requested by the login. The login failed

我真的很沮丧,这很简单但对我不起作用。我正在尝试连接到我的 SQL 服务器,当 运行 SSMS 时我不需要用户名和密码。我的服务器名称是 HP\SQLEXPRESS,我使用的是以下连接字符串:

string connectionString = "Data Source=HP\SQLEXPRESS;Initial Catalog=Students.mdf;Integrated Security=SSPI;";

我收到以下错误:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: Cannot open database "Students.mdf" requested by the login. The login failed.

Login failed for user 'HP\Aymen'.

当我指定我的数据库的完整地址时,如下所示:

string connectionString = "Data Source=HP\SQLEXPRESS;Initial Catalog=c:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\Students.mdf;Integrated Security=SSPI;";

它也给我同样的错误。

有什么建议吗?

尝试使用sa登录访问数据库

User ID=sa;
Password="your password without quotes"; 

data source=.

在您的连接字符串中

更新的连接字符串

FOR WINDOWS 授权

string connectionString = "Data Source=.;Initial Catalog=Students;Integrated Security=SSPI;"

FOR SQL AUTH.

string connectionString="Data Source=.;User ID=sa;
Password=; Initial Catalog=Students; " providerName="System.Data.SqlClient";

试试这个

我认为您正在使用 Windows 身份验证

string connectionString = "Data Source=HP\SQLEXPRESS;
Initial Catalog=Students;Integrated Security=SSPI;" 

我认为您对该用户有权限问题。

您是否尝试过使用其他用户(管理员用户)登录该数据库?

  1. 使用您的管理员用户登录 ssms。
  2. 在安全下,将服务器角色和用户映射更改为您想要的特定用户,然后再次尝试登录。忘记授予该用户对 "master".
  3. 的权限

当您从 SSMS 连接时,您拥有管理员权限。 我认为 运行 您的程序的用户不是这种情况。

但是,我建议您使用 create login 创建一个特定的用户 然后,只需将您的参数添加到 sql server connection string

这里似乎是身份验证问题。您也应该在连接字符串中指定用户 ID。

string connectionString = "Data Source=HP\SQLEXPRESS;Initial Catalog=Students;Integrated Security=SSPI;User ID=PCName\WindowsUser;";

如果还是不行,再试试这个。

string connectionString = "Server=HP\SQLEXPRESS;Database=Students;Trusted_Connection=True;

问题已解决。看来问题是因为我已经使用 Entity Framework 模型连接到数据库。当我删除它并再次 运行 应用程序时,一切正常。