从Windows服务应用程序访问数据到SQL Server数据库?

时间:2016-01-13 16:20:32

标签: c# sql-server windows

我尝试使用Windows服务应用程序将数据插入到我的数据库中,但我未能达到结果。该服务运行。连接字符串是正确的,但无法插入数据。

我试图在网上进行研究......到目前为止还没有找到很好的尝试。有没有人有解决方案?

谢谢。

// this is my service class
public partial class sacc : ServiceBase
{
    SqlConnection con;
    SqlCommand com;

    string query = string.Empty;

    SqlDataReader reader;

    GlobalConnector gc = new GlobalConnector();
    SerialPort sp;
    string temp;

    public sacc()
    {
        InitializeComponent();
        //Control.CheckForIllegalCrossThreadCalls = false;
    }

   public sacc(string[] args)        
   {
       this.CanStop = true;
       this.CanPauseAndContinue=true;
       InitializeComponent();            
       string eventSourceName = "MySource";            
       string logName = "MyNewLog";            

       if (args.Count() > 0)            
       {                
           eventSourceName = args[0];            
       }            

       if (args.Count() > 1)            
       {                
           logName = args[1];           
       }            

       eventLog1 = new System.Diagnostics.EventLog();            

       if (!System.Diagnostics.EventLog.SourceExists(eventSourceName))            
       {               
           System.Diagnostics.EventLog.CreateEventSource(eventSourceName, logName);           
       }           

       eventLog1.Source = eventSourceName;           
       eventLog1.Log = logName;       
    }

    Timer timer1 = new Timer();

    protected override void OnStart(string[] args)
    {
        timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
        timer1.Interval = 10000;
        timer1.Enabled = true;
        timer1.Start();
    }

    private void timer1_Elapsed(object sender, EventArgs e)
    {
        using (con = new SqlConnection(gc.connnectionstring))
        {
            con.Open();

            sp = new SerialPort(AutodetectArduinoPort(), 9600);

            sp.Open();
            sp.Parity = Parity.None;
            sp.StopBits = StopBits.One;
            sp.Handshake = Handshake.None;
            sp.ReadTimeout = 10000;
            sp.DataReceived += new SerialDataReceivedEventHandler(datareceive);

            query = "delete from temperature";

            using (var com = new SqlCommand(query, con))
            {
                com.ExecuteNonQuery();
            }

            con.Close();
        }
    }

    private void datareceive(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        int countbt = sp.BytesToRead;

        if (countbt > 3)
        {
            byte[] recbyte = new byte[countbt];

            sp.Read(recbyte, 0, countbt - 1);

            char deg = (char)176;

            temp = recbyte[2].ToString() + " " + deg + " Celcius";

            //  label3.Text = ASCIIEncoding.ASCII.GetString(recbyte,2,1);

        }
    }

    private string AutodetectArduinoPort()
    {
        ManagementScope connectionScope = new ManagementScope();
        SelectQuery serialQuery = new SelectQuery("SELECT * FROM Win32_SerialPort");
        ManagementObjectSearcher searcher = new ManagementObjectSearcher(connectionScope, serialQuery);

        try
        {
            foreach (ManagementObject item in searcher.Get())
            {
                string desc = item["Description"].ToString();
                string deviceId = item["DeviceID"].ToString();

                if (desc.Contains("Arduino"))
                {
                    return deviceId;
                }
            }
        }
        catch (ManagementException e)
        {
            /* Do Nothing */
        }

        return null;
    }

这是我的projectinstaller.cs

 private void serviceProcessInstaller1_AfterInstall(object sender, InstallEventArgs e)
    {
        this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
        serviceProcessInstaller1.Username = null;
        serviceProcessInstaller1.Password = null;
    }

非常感谢。

1 个答案:

答案 0 :(得分:0)

需要更多详细信息,但从过去的经验来看,它最有可能成为安全问题!!这里是解决它的细节

您需要检查Windows服务属性并检查其运行的凭据。

SQL Server需要添加该用户才能访问数据库。

例如,如果您使用SYSTEM,则将SYSTEM添加到SQL Server角色,并授予其访问您要访问的数据库的权限。

这应解决您的问题

enter image description here