如何从Windows服务访问SQL数据库?

5

我正在尝试开发一个适用于Windows 10(64位)的Windows服务,旨在定期将记录插入本地MS SQL Server(v.11)。

它已经安装并成功运行,但没有记录被插入。我尝试使用 System.Timers.TimerSystem.Threading.Timer

我还尝试在服务启动事件上进行插入。但这也没有起作用。

下面是我的代码:

public partial class Service1 : ServiceBase
{
    // System.Timers.Timer timer;
    System.Threading.Timer threadTimer;
   
    public Service1()
    {
        InitializeComponent();
    }


    //UPDATE: I checked the following method code in a console application. It works fine.
    private void InsertRecord()
    {
        try
        {
            using (SqlConnection connection = new SqlConnection("Server=.;Database=TestDb; Trusted_Connection=True;"))
            {
                using (SqlCommand command = new SqlCommand())
                {
                    command.Connection = connection;
                    command.CommandText = "Insert into .....')";
                    connection.Open();
                    command.ExecuteNonQuery();
                    connection.Close();
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

    protected override void OnStart(string[] args)
    {
        InsertRecord(); //This line not executed also.

        TimeSpan tsInterval = new TimeSpan(0, 2, 0); //2 minute interval.
        threadTimer = new Timer(new TimerCallback(threadTimer_Elapsed)
            , null, tsInterval, tsInterval);


        //timer = new System.Timers.Timer();
        //timer.Interval = 10000;
        //timer.Elapsed += Timer_Elapsed;
        //timer.Enabled = true;
        //timer.Start();
    }

    private void threadTimer_Elapsed(object state)
    {
         InsertRecord();
    }

    //private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    //{
    //      InsertRecord()
    //}

    protected override void OnStop()
    {
        threadTimer.Change(Timeout.Infinite, Timeout.Infinite);
        threadTimer.Dispose();
        threadTimer = null;

        //timer.Stop();
    }
}

我在这里错过了什么?


4
一个空的catch块是一种保持不知情的好方法... - H H
如果未能到达 OnStart,则服务启动失败。请查看Windows事件日志。 - user585968
1
此外,如果您添加某种日志记录功能以便在运行服务时查看发生的错误,将会极大地帮助。 - NightOwl888
您还可以将服务进程附加到项目并自行进行调试,以查看问题所在。 - SᴇM
@ SeM - ՍեՄ - 插入代码块运行良好。 - Kafi
显示剩余2条评论
3个回答

8
在您的SQL Server中,允许NT AUTHORITY/SYSTEM担任sysadmin服务器角色。

按照以下截图操作-

enter image description here

enter image description here


1
将服务的“运行为”设置更改为您自己的个人帐户。这将提供与控制台测试相同的安全环境。这将允许服务获得登录 SQL Server 的权限。
然后将服务更改为“本地系统”或类似设置,它将失败 - 您需要授予“本地系统”访问数据库的权限。
此外 - 空的Catch块是您发布到SO的原因 - 如果您编写了最简单的错误处理程序和记录器,您将得到答案。

0

您没有提供关于连接字符串的很多信息,但正如@NightOwl888所指出的那样,问题可能与您使用的Trusted_Connection=True有关。

如果您正在使用Sql身份验证(而不是Windows身份验证)连接到Sql服务器,我认为您需要设置Trusted_Connection=False

这应该允许使用您的连接字符串凭据(而不是机器名称/Windows服务帐户等)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接