我连接到asp.net mvc 3项目中的数据库。此外,我在我的解决方案中有一个Windows服务项目,在某些事件中将数据写入此数据库。如何打开已经在c#中使用的SQL Server数据库的连接?
的困难在于,当从Windows服务项目中的代码需要连接到数据库,我得到SqlException
:
无法打开数据库“网上商店”的登录请求。登录失败。用户'NT AUTHORITY \ SYSTEM'登录失败。
下面是从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 [email protected] WHERE [email protected]";
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可用连接。连接已关闭。
问题:如何开到已经连接在另一个项目中的SQL Server数据库的连接?
编辑1:我用下面的代码在我的数据库中创建新的登录和新用户:
CREATE LOGIN user1
WITH PASSWORD = 'password1';
GO
CREATE USER user1 FOR LOGIN user1;
GO
比我想附上我在服务器资源管理器DB:我选择“使用SQL服务器自动验证“并输入用户名:user1,密码:password1。
我也得到:
附加到以下信息数据库失败的尝试:
登录失败,用户USER1“。
编辑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:我在服务中设置了我的用户名和密码。msc和processInstaller“帐户”属性我留下了“本地系统”。它运行,但是当我改变形象(和事件处理程序试图访问我的数据库)我得到:
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*
和Windows服务中使用的连接字符串中:User Id=user1;PASSWORD=password1;
?
当您在自己的凭证/身份下调试代码时,登录异常仍然发生吗?另外,我很少在字符串上使用@指令,是否会改变'\'的行为,使'\ v'正确或者它应该是'\\ v'? (再次,我很少使用@并且不知道。) – 2013-02-26 16:15:12
在数据库中创建新登录并在连接字符串中传递用户名和密码。 – 2013-02-26 16:16:07
您是否尝试过使用网络服务帐户打开它?该帐户应该绕过传统登录。因为它将像网络上的计算机一样工作,所以它不应该有与SQL连接的问题。 http://msdn.microsoft。com/en-us/library/windows/desktop/ms684272%28v = vs.85%29.aspx – Greg 2013-02-26 16:16:35