使用Windows服务实时更新数据库中的数据

时间:2018-02-27 23:26:24

标签: c# mysql windows-services

我编写了一个Windows服务来从CSV文件中获取数据并将它们写回数据库。它按照我的预期顺利运作。但是更新数据存在问题。我的目的是立即将CSV文件的更改更新回数据库。虽然当我更改csv文件中的数据时,我的Windows服务在后台运行,但由于某种原因它不会更新数据库。我甚至试图重启Windows服务。但也没有运气。我可以在下面插入我的编码。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;

namespace abpservice
{
    public partial class Service1 : ServiceBase
    {
        private Timer timer1 = null;



        public Service1()
        {
            InitializeComponent();
        }
        public void onDebug()
            {
                OnStart(null);
            }
        protected override void OnStart(string[] args)
        {
            timer1 = new Timer();
            this.timer1.Interval = 30000; //every 30 seconds
            this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
            timer1.Enabled = true;
            library.WriteErrorLog("windows service started");
        }

        private void timer1_Tick(object sender, ElapsedEventArgs e)
        {
            string connStr = "server=localhost;user=root;database=database;port=3306;password=123456";
            MySqlConnection conn = new MySqlConnection(connStr);

            MySqlBulkLoader bl = new MySqlBulkLoader(conn);
            bl.TableName = "jobs";
            bl.FieldTerminator = ",";
            bl.LineTerminator = "\n";
            bl.FileName = @"C:\Users\source\repos\WindowsService1\WindowsService1\bin\Debug\jobs.csv";

            //bl.FileName = bl.FileName.Replace(@"\\", @"\ \");
            bl.NumberOfLinesToSkip = 1;

            try
            {
                Console.WriteLine("Connecting to MySQL...");
                conn.Open();

                // Upload data from file
                int count = bl.Load();
                Console.WriteLine(count + " lines uploaded.");





                conn.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.WriteLine("Done.");
            library.WriteErrorLog("Timer ticked and some  jobs have been done sucessfully");
        }

        protected override void OnStop()
        {
            timer1.Enabled = false;
            library.WriteErrorLog("Test window service stopped");
        }
    }
}

如果有人能够理解为什么CSV文件中的更改没有在数据库中实时更新,请不要犹豫,给出答案。这可能对我完成这项任务有很大帮助。

0 个答案:

没有答案
相关问题