首页 > 解决方案 > 如何在 Windows 服务中执行 SQL 命令?

问题描述

所以我在我的程序中创建了服务。我需要这项服务来更新我的表格。它应该像检查短信的发送报告一样工作。

所以在这个服务中,我想从短信网关执行api来获取数据,然后将它们插入到SQL中的日志表中。

我设法在服务中创建了计时器,并进行了一些事件日志更新。所以我的服务还活着,但问题是当我试图用我的 sql 服务器做任何事情时,它可能不会执行任何事情,我真的不知道为什么。

服务:

    public partial class Service1 : ServiceBase
{
    private int eventId = 1;
    DataSet ds = new DataSet();
    SqlConnection cs = new SqlConnection("Data Source=lvrabel; Initial Catalog=EagleTest; Integrated Security=TRUE;");
    SqlDataAdapter da = new SqlDataAdapter();



    public Service1()
    {
        InitializeComponent();

        eventLog1 = new EventLog();
        if (!EventLog.SourceExists("MySource"))
        {
            EventLog.CreateEventSource("MySource", "MyNewLog");
        }
        eventLog1.Source = "MySource";
        eventLog1.Log = "MyNewLog";
    }

    protected override void OnStart(string[] args)
    {
        eventLog1.WriteEntry("In OnStart");

        Timer timer = new Timer();
        timer.Interval = 60000; // 60 seconds
        timer.Elapsed += new ElapsedEventHandler(this.GetReports);
        timer.Start();          
    }

    protected override void OnStop()
    {
        eventLog1.WriteEntry("In OnStop.");
    }

    public void OnTimer(object sender, ElapsedEventArgs args)
    {
        // TODO: Insert monitoring activities here.
       // eventLog1.WriteEntry("Monitoring the System", EventLogEntryType.Information, eventId++);
    }

    public void GetReports(object sender, ElapsedEventArgs args)
    {
        //SqlCommand selectTelephone = new SqlCommand("select telephone from Contacts where LASTNAME = 'test'", cs);
        //cs.Open();
        //SqlDataAdapter da = new SqlDataAdapter(selectTelephone);
        //DataTable dt = new DataTable();
        //da.Fill(dt);

        //foreach (DataRow dr in dt.Rows)
        //{
        //    eventLog1.WriteEntry(dr["telephone"].ToString(), EventLogEntryType.Information, eventId++);
        //}
        //cs.Close();


        cs.Open();
        da.InsertCommand = new SqlCommand("insert into Log(IDContacts, IDEvent, Description, smsID) VALUES('5', '3', 'SMS OUT', '123')", cs); // dodelat id contacts

        da.InsertCommand.ExecuteNonQuery();
        cs.Close();
    }
}

是否有可能如何对服务进行故障排除,或者您是否在我的代码中看到任何错误?(atm我只有insertCommand。我稍后将http api添加到代码中)

https://imgur.com/a/O5T78E2 - 我正在使用的安装程序的 imgur 图像

添加的解决方案:

所以所有的问题都出在用户权限上。我使用的是本地系统服务,而不是网络服务。现在一切正常。

标签: c#sql.netwpfwindows-services

解决方案


如果您对系统有足够的权限,您可以在服务运行时主动调试服务以查看可能发生的异常。您可以在此处参考接受的答案,或者在您的回调中简单地进行以下调用OnStart()

System.Diagnostics.Debugger.Break();

当你启动你的服务时,你应该得到一个提示,表明发生了未处理的异常。

在此处输入图像描述

单击是选项,对 UAC 提示回答是,选择要使用的 Visual Studio 实例,然后正常调试。这有望让人们更清楚地了解正在发生的事情,而不必猜测。

高温高压


推荐阅读