简体   繁体   English

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

[英]How to access a SQL database from a Windows service?

I am trying to develop an windows service for Windows 10 (64bit), which intends to insert record in local MS SQL Server (v.11) periodically.我正在尝试为 Windows 10(64 位)开发一个 Windows 服务,它打算定期在本地 MS SQL Server(v.11)中插入记录。

It installed and ran successfully, but no record is inserted.它安装并运行成功,但没有插入任何记录。 I tried both System.Timers.Timer and System.Threading.Timer .我尝试了System.Timers.TimerSystem.Threading.Timer

I also tried to insert on service start event.我还尝试在服务启动事件上插入。 But that also didn't work.但这也不起作用。

Here is my code:这是我的代码:

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();
    }
}

What did I miss here?我在这里错过了什么?

In your SQL Server, allow NT AUTHORITY/SYSTEM to server Role as sysadmin.在您的 SQL Server 中,允许 NT AUTHORITY/SYSTEM 以 sysadmin 身份服务 Role。

Follow the screenshots-按照屏幕截图-

在此处输入图片说明

在此处输入图片说明

Change the Run As setting on the service to run as your own personal account.更改服务上的运行方式设置以作为您自己的个人帐户运行。 This will provide the same security environment as your console test.这将提供与您的控制台测试相同的安全环境。 This will allow the service permission to log into SQL Server.这将允许服务权限登录到 SQL Server。

Then change the service to "Local System" or similar and it will fail - you need to then grant "Local System" rights to access the database.然后将服务更改为“本地系统”或类似服务,它将失败 - 您需要授予“本地系统”访问数据库的权限。

Also - an empty Catch block is the reason you are posting to SO - if you coded the simplest of error handler and loggers you would get your answer.此外 - 一个空的 Catch 块是您发布到 SO 的原因 - 如果您编写了最简单的错误处理程序和记录器,您将得到答案。

You did not provide a lot of information about your connection string, but as @NightOwl888 pointed out, the problem may have to do with your use of Trusted_Connection=True .您没有提供有关连接字符串的大量信息,但正如@NightOwl888 指出的那样,问题可能与您使用Trusted_Connection=True 有关

If you are using Sql Authentication (as opposed to Windows Authentication) to connect to the Sql server, I believe you need to set Trusted_Connection=False .如果您使用 Sql 身份验证(而不是 Windows 身份验证)连接到 Sql 服务器,我相信您需要设置Trusted_Connection=False

This should allow your connection string credentials to be used (rather than the machine name/Windows service account/etc.).这应该允许使用您的连接字符串凭据(而不是机器名称/Windows 服务帐户/等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM