数据库
首页 > 数据库> > 从Windows服务访问数据库

从Windows服务访问数据库

作者:互联网

我正在尝试为Windows 10(64位)开发Windows服务,该服务旨在定期在本地MS SQL Server(v.11)中插入记录.

它已安装并成功运行.但是没有插入任何记录.我尝试了System.Timers.Timer和System.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();
    }
}

我在这里想念什么?

解决方法:

在您的SQL Server中,允许NT AUTHORITY / SYSTEM以sysadmin的身份服务器角色.

按照屏幕截图-

enter image description here

enter image description here

标签:windows-10,windows-services,c,sql-server
来源: https://codeday.me/bug/20191110/2015395.html