C# 在Visual Studio 2017中使用Windows服务访问MySQL数据库

C# 在Visual Studio 2017中使用Windows服务访问MySQL数据库,c#,mysql,windows,service,C#,Mysql,Windows,Service,我创建了一个带有计时器的windows服务,我想访问mysql数据库。计时器工作得很好。我配置数据库连接。 测试连接成功 名称空间贝拉塞拉 { 公共部分类Service1:ServiceBase { 定时器=新定时器(); string connectionString=“server=belaserra.com;用户id=belaserra\u user;persistsecurityinfo=True;database=belaserra\u imix”; //string connect

我创建了一个带有计时器的windows服务,我想访问mysql数据库。计时器工作得很好。我配置数据库连接。

测试连接成功

名称空间贝拉塞拉 { 公共部分类Service1:ServiceBase { 定时器=新定时器(); string connectionString=“server=belaserra.com;用户id=belaserra\u user;persistsecurityinfo=True;database=belaserra\u imix”; //string connectionString2=“Server=belaserra.com;Database=belaserra\u imix;Uid=belaserra\u user;Pwd=pass;”; mysqlcon

    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        con = new MySqlConnection(connectionString);

        try
        {
            con.Open();
            WriteToFile("Service is started at " + DateTime.Now);
        }
        catch (Exception ex)
        {
            WriteToFile("Error connecting belaserra database: " + ex.Message);
        }
        finally
        {
            con.Close();
        }
        timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
        timer.AutoReset = true;
        timer.Interval = 5000; //number in miliseconds  
        timer.Enabled = true;
        timer.Start();
    }

    protected override void OnStop()
    {
        WriteToFile("Service is stopped at " + DateTime.Now);
        timer.AutoReset = false;
        timer.Enabled = false;
    }

    private void OnElapsedTime(object source, ElapsedEventArgs e)
    {
        WriteToFile("Service is recall at " + DateTime.Now);
        Check_new_imoveis();
    }

    public void WriteToFile(string Message)
    {
        string path = "C:\\Belaserra_service_logs";

        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        string filepath = "C:\\Belaserra_service_logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";

        if (!File.Exists(filepath))
        {
            // Create a file to write to.   
            using (StreamWriter sw = File.CreateText(filepath))
            {
                sw.WriteLine(Message);
            }
        }
        else
        {
            using (StreamWriter sw = File.AppendText(filepath))
            {
                sw.WriteLine(Message);
            }
        }
    }

    public void Check_new_imoveis()
    {

        WriteToFile("DO STUFF!!!");

    }

}
}

“con.Open”在.txt文件中给了我一个异常错误:“使用方法'mysql_native_password'对用户'belaserra_user'的主机'belaserra.com'进行身份验证失败,消息为:用户'belaserra_user'的访问被拒绝@'188.251.3.177'(使用密码:否)”


我尝试使用“connectionString2”进行连接,该服务立即启动和结束。

您是否从数据库服务器中捕获了任何错误? 您的计算机上是否安装了Mysql驱动程序

我建议您修改:

protected override void OnStart(string[] args)
    {
        WriteToFile("Service is started at " + DateTime.Now);
        timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
        timer.Interval = **TimeStamp.FromSeconds(X)**; //number in miliseconds  
        timer.Enabled = true;
    }

我重新创建了您的代码,请尝试这对我有用:

public partial class Service1 : ServiceBase { 

  private Timer timer {get;private set;} = new Timer();
  string filepath = "C:\\Belaserra_service_logs";
  string ConnectionString = "server=belaserra.com;database=belaserra_imix;uid=belaserra_user;pwd=pass;";
  MySqlConnection con;
    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        Directory.CreateDirectory(filepath);
        con = new MySqlConnection(ConnectionString);
        con.open();//on connection onetime
        WriteToFile("Service is started at " + DateTime.Now);
        timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
        timer.Interval = 5000; //number in miliseconds  
        timer.Enabled = true;
        //You forget to start timer.
        timer.Start();
    }

    protected override void OnStop()
    {
        con.open();
        WriteToFile("Service is stopped at " + DateTime.Now);
    }

    private void OnElapsedTime(object source, ElapsedEventArgs e)
    {
        WriteToFile("Service is recall at " + DateTime.Now);
        Check_new_imoveis();
    }

    public void WriteToFile(string Message)
    {

        filepath = Path.Combine(filepath,"ServiceLog_" + DateTime.Now.ToString("yyy_MM_dd")+".txt");
        File.AppendAllText(filepath);

    }

    public void Check_new_imoveis()
    {
        // TO DO : Manipulate your database here
    }

}

这不会帮助OP解决他的问题。从技术上来说,你应该可以做一些TimeSpan.FromSeconds(5)。Total毫秒,但这将与OPYep相同,我知道,但我正在等待捕获的异常(从windows事件查看器)。编译中没有错误。但是日志文件只写“服务在”+DateTime时被调用。现在每隔5秒。我希望它也能写“连接成功!”。我已经安装了驱动程序,我在VS 2017中配置了连接,并成功地进行了“测试连接”。受保护的override void OnStop(){con.Close();//Close here WriteToFile(“服务在”+DateTime.Now);}我尝试了你的代码,服务立即开始和结束。我有新代码并编辑了答案…问题是拒绝用户访问。问题是拒绝用户访问。。。