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

标签 c# sql-server windows-services windows-10

我正在尝试为 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();
    }
}

我在这里错过了什么?

最佳答案

在您的 SQL Server 中,允许 NT AUTHORITY/SYSTEM 将服务器角色作为系统管理员。

按照截图-

enter image description here

enter image description here

关于c# - 如何从 Windows 服务访问 SQL 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46967912/

相关文章:

c# - 链接服务器和 Entity Framework 。还有其他选择吗?

sql-server - silverlight 5 功能请求列表?

SQL,获取外键值。外键引用同一张表

c# - 无法在 Windows 7 中使用 C# 中的窗口服务计算系统空闲值

c# - Entity Framework 6 Code First - 对树结构的评论

c# - 如何限制 WebAPI 中的 OData 结果

c# - 使用 PostSharp,无法让 Multicast 为 WinForm 控件单击处理程序工作

c# - 从 c# 运行仅签名的 powershell 脚本

c# - 优雅地处理 Windows 服务的关闭

c# - Windows 服务的后台 worker