-1

我有一个带有计时器的 Windows 服务程序,经过的事件从我的默认测试中触发,但它不会更新数据库。相同的代码适用于 Windows 窗体按钮单击事件。这是代码。使用 3 层架构和 sql server 2012。

namespace DALStations
{
class GetUpdate
{
    DALConnection connectstring;

    public GetUpdate()
    {
        connectstring = new DALConnection();
    }

             public void  UpdateCommands() //SqlCommand
            {

                SqlCommand authorize = new SqlCommand();

                 authorize.CommandText = "dbo.UpdateTest";
                authorize.CommandType = CommandType.StoredProcedure;
                authorize.Connection = connectstring.GetConnection();


                 authorize.Connection.Open();                    
                authorize.ExecuteNonQuery();

                 authorize.Connection.Close();

            }

}
}

巴尔

namespace BALStations
{
class BAL
{

    //public void UpdateTest()
    //{
    //    new DALTest().Updatetest();
    //}


    public void CallUpdateProcedure()
    {

        new GetUpdate().UpdateCommands();
    }
  }
}

 Service Layer or UI

namespace Stations
{
public partial class Service1 : ServiceBase
{
    private static System.Timers.Timer aTimer;


      public Service1()
    {
        InitializeComponent();

    }



    protected override void OnStart(string[] args)
    {
        Process();

    }

    public void Process()
    {
        aTimer = new System.Timers.Timer(10000);

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(timer1_Elapsed);

        // Set the Interval to 30 seconds (30000 milliseconds).
        aTimer.Interval = 3000;
        aTimer.Enabled = true;

        using (StreamWriter writer = new StreamWriter(@"C:\Users\Joe\Desktop\Summit Works\Authorized Timer\Details.txt", true))
        {
            writer.WriteLine("Service Start {0}", DateTime.Now, true);
        }
        aTimer.Start();
    }

    protected override void OnStop()
    {
        this.timer1.Enabled = false;

    }

    private void timer1_Elapsed(object sender,
 System.Timers.ElapsedEventArgs e)
    {         

       BAL bal = new BAL();
       bal.CallUpdateProcedure(); 

    }     


}
}
4

1 回答 1

1

这是由于权限。

Windows 服务以什么身份运行,它是否对存储过程具有执行权限?

转到服务并检查您的服务的身份。它可能运行为NETWORK SERVICELOCAL SYSTEM

USE MYDatabase
GO

CREATE LOGIN [NT AUTHORITY\NETWORK SERVICE] FROM WINDOWS;
GO

CREATE USER [NETWORK SERVICE] FOR LOGIN [NT AUTHORITY\NETWORK SERVICE]
    WITH DEFAULT_SCHEMA = YourDatabase;
GO

GRANT EXECUTE ON dbo.UpdateTest TO  [NETWORK SERVICE];

您可以通过添加到 dbo 角色来授予“更多”权限(但我不会走这条路):

EXEC sp_addrolemember 'dbo', 'NETWORK SERVICE'
于 2013-08-05T02:52:44.810 回答