zohaib khan

zohaib khan

  • NA
  • 26
  • 37.1k

Access Mysql database from Windows Service.

Nov 16 2011 4:43 AM
Hi,

I have developed Console application and connect to mysql database using reference DLL (MySql.Data.dll) OR MSI installer from following url

http://dev.mysql.com/downloads/connector/net/5.2.html

It is working fine.

I have developed mysql connection from windows service and try to log using Event log but it is not working.

No log information in event log and windows service not connecting to mysql database.

any solution to this problem?

Following is the code related to mysql connection.

using MySql.Data;
using MySql.Data.MySqlClient;
using System.Diagnostics;

public static void mysqlConnection()
{
    string sSource;
    string sLog;
   // string sEvent;
   
    sSource = "Windows Service";
    sLog = "Windows Service Application";
   // sEvent = "Sample Event";

    try
    {
       
        if (!EventLog.SourceExists(sSource))
            EventLog.CreateEventSource(sSource, sLog);

       // EventLog.WriteEntry(sSource, sEvent);
       // EventLog.WriteEntry(sSource, sEvent,
         //   EventLogEntryType.Warning, 234);

        string MyConString = "SERVER=localhost;" +
                "DATABASE=databasename;" +
                "UID=root;" +
                "PASSWORD=;";
        MySqlConnection connection = new MySqlConnection(MyConString);
        MySqlCommand command = connection.CreateCommand();

        MySqlDataReader Reader;
        command.CommandText = "select * from tablename";
        connection.Open();
        Reader = command.ExecuteReader();
        while (Reader.Read())
        {

        }
        connection.Close();
    }
    catch (Exception ex)
    {
        EventLog.WriteEntry(sSource, ex.Message);
        Console.WriteLine(ex.Message);
    }
}