我连接到asp.net mvc 3项目中的数据库。而且,我的解决方案中有一个windows服务项目,它会在某些情况下将数据写入该数据库。
困难在于,当windows服务项目的代码需要连接到数据库时,我得到了SqlException:
无法打开登录请求的数据库"WebStore“。登录失败。登录失败的用户'NT权限\系统‘。
以下是windows服务的代码:
public static string GetConnectionString()
{
return @"Data Source=(LocalDB)\v11.0; DataBase=WebStore;
AttachDbFilename=myDbFullPath;
Integrated Security=True;Connect Timeout=30";
}在写入数据库的事件处理程序中:
using (var conn = new SqlConnection(GetConnectionString()))
{
conn.Open();
var productId = Convert.ToInt32(Regex.Match(e.Name, @"\d+").Value);
const string cmd1 = "UPDATE Products SET ImageModifiedDate=@date WHERE ProductId=@productId";
using (var command = new SqlCommand(cmd1, conn))
{
command.Parameters.AddWithValue("@productId", productId);
command.Parameters.AddWithValue("@date", DateTime.Now);
command.ExecuteNonQuery();
}
}异常发生在conn.Open();行中。如果我评论这一行,command.ExecuteNonQuery();中将出现新的异常:
InvalidOperationException: ExecuteNonQuery需要打开和可用的连接。连接关闭。
问题:如何打开已附加到另一个项目中的Server数据库的连接?
编辑1:我使用以下代码在DB中创建新登录名和新用户:
CREATE LOGIN user1
WITH PASSWORD = 'password1';
GO
CREATE USER user1 FOR LOGIN user1;
GO而不是在服务器资源管理器中附加我的数据库:我选择“使用”并输入用户名: user1,密码: password1。
我得到了:
试图附加到数据库的尝试失败,提供了以下信息: 用户“user 1”登录失败。
编辑2:我设置了以下属性:
processInstaller.Username = "user1";
processInstaller.Password = "password1";并在cmd中运行:
installutil /name=user1 /password=password1 MyService.exe我得到了System.ComponentModel.Win32.Exception:
the comparison between user names and security identifiers haven't been executed.
我做错什么了?
编辑3:我在services.msc和processInstaller "Account“属性中设置了我的用户名和密码。它会运行,但是当我更改映像(以及试图访问我的数据库的事件处理程序)时,我得到:
Cannot attach file 'C:\Users\Aleksey\repos\working-copy\WebStore\WebStore\App_Data\WebStore.mdf' as database 'WebStore' because this file is already in use for database 'C:\USERS\ALEKSEY\REPOS\WORKING-COPY\WEBSTORE\WEBSTORE\APP_DATA\WEBSTORE.MDF',
在连接字符串中,我添加了我在数据库中创建的用户凭据:
User Id=user1;PASSWORD=password1;
此外,当我试图在服务器资源管理器中添加连接并使用Sql Server Authentication并输入user1和password1时,我从编辑1获得消息。
我应该在服务器资源管理器*Windows Authentication*和连接字符串:User Id=user1;PASSWORD=password1;中的windows服务中使用吗?
发布于 2013-02-27 13:18:09
Cannot open database "WebStore" requested by the login. The login failed. Login failed for user 'NT AUTHORITY\SYSTEM'.之所以会出现这种情况,是因为您的服务正在使用LocalSystem帐户运行,并且您正在使用集成安全性连接到server,并且系统不应该在那里进行访问。因此,有三个回应:
第二错误
InvalidOperationException: Opened and available connection is needed for ExecuteNonQuery. Connection is closed.是由第一个错误引起的,未能打开连接就会引发这种情况。如果没有打开的连接,您就无法执行任何操作,ADO.Net要确保这一点。
因此,第一个错误是唯一重要的错误。
我建议您使用选项二,因为这是安全实践中最好的,而且由于您是在集成安全环境中运行,所以您不必存储任何密码,当您在几个具有不同数据库、用户、密码等不同环境的环境中使用应用程序时,这是一个优点。每个环境只需要一个用户,权限就可以设置了。
https://stackoverflow.com/questions/15093908
复制相似问题