- ติดตั้ง MySql.Data ผ่าน NuGet
- สร้างโฟลเดอร์ mysql
- สร้างคลาส mysql/sql.cs
- สร้างคลาส mysql/qry.cs
- แก้ไขไฟล์ App.config
- แก้ไขไฟล์ Program.cs
1.ติดตั้ง MySql.Data ผ่าน NuGet
PM> Install-Package MySql.Data -Version 6.9.12
2.สร้างโฟลเดอร์ mysql
3.สร้างคลาส mysql/sql.cs
using MySql.Data.MySqlClient;
using System;
using System.Configuration;
using System.Data;
using System.Reflection;
using System.Text.RegularExpressions;
namespace ConsoleApp1.mysql
{
class sql
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static string connMySql = ConfigurationManager.AppSettings.Get("connMySql");
public static DataTable ExecuteQuery(string query)
{
query = Regex.Replace(query, @"\s+", " ");
log.Debug(query);
try
{
using (MySqlConnection conn = new MySqlConnection(connMySql))
{
conn.Open();
MySqlDataAdapter da = new MySqlDataAdapter(query, conn);
System.Data.DataSet ds = new System.Data.DataSet("Names");
da.Fill(ds);
DataTable dt = ds.Tables[0];
conn.Close();
log.Debug(string.Format(" found {0} record.", dt.Rows.Count));
return dt;
}
}
catch (MySqlException ex)
{
log.Error(ex.Message);
return null;
}
}
public static DataTable ExecuteReader(string query)
{
//log.Info(string.Format(" '{0}'", connIIA.Split(';')[0]));
query = Regex.Replace(query, @"\s+", " ");
log.Debug(query);
DataSet ds;
try
{
// Open a connection
using (MySqlConnection conn = new MySqlConnection(connMySql))
{
conn.Open();
using (MySqlTransaction trans = conn.BeginTransaction(IsolationLevel.ReadUncommitted))
{
// Create an SQL command
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
cmd.Transaction = trans;
//log.Debug(string.Format("cmd.CommandTimeout='{0}'", cmd.CommandTimeout));
cmd.CommandTimeout = 5000;
//log.Debug(string.Format("cmd.CommandTimeout='{0}'", cmd.CommandTimeout));
using (MySqlDataReader dr = cmd.ExecuteReader())
{
// Write the data to the console
//while (dr.Read())
//{
// Console.WriteLine(dr["lotno"].ToString());
//}
ds = new System.Data.DataSet("Names");
while (!dr.IsClosed)
ds.Tables.Add().Load(dr);
dr.Close();
DataTable dt = ds.Tables[0];
// Close the connection
conn.Close();
log.Debug(string.Format(" found {0} record.", dt.Rows.Count));
return dt;
}
}
}
}
}
catch (MySqlException ex)
{
log.Error(ex.Message);
return null;
}
}
public static string ExecuteNonQuery(string query)
{
query = Regex.Replace(query, @"\s+", " ");
log.Debug(query);
try
{
string result = "";
using (var conn = new MySqlConnection(connMySql))
{
conn.Open();
using (MySqlTransaction myTrans = conn.BeginTransaction(IsolationLevel.ReadCommitted))
{
// Assign transaction object for a pending local transaction
using (MySqlCommand myCommand = new MySqlCommand())
{
myCommand.Connection = conn;
myCommand.Transaction = myTrans;
try
{
myCommand.CommandText = query;
myCommand.ExecuteNonQuery();
myTrans.Commit();
result = "success";
log.Info(result);
}
catch (Exception ex)
{
myTrans.Rollback();
result = ex.Message;
log.Error(ex.Message);
}
}
}
}
return result;
}
catch (MySqlException ex)
{
log.Error(ex.Message);
return null;
}
}
} // end class
}
4.สร้างคลาส mysql/qry.cs
using System.Reflection;
namespace ConsoleApp1.mysql
{
public class qry
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static string QuerySelectData(string param1)
{
log.Info(string.Format("Parameter ({0})", param1));
string query = string.Format(@"", param1);
return query;
}
public static string QuerySelectData(string param1, string param2)
{
log.Info(string.Format("Parameter ({0}, {1})", param1, param2));
string query = string.Format(@"", param1, param2);
return query;
}
} // end class
}
5.แก้ไขไฟล์ App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="connMySql" value="server=xxx.xxx.xxx.xxx;database=[dbname];uid=[userid];pwd=[userpass];" />
</appSettings>
<system.data>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient" />
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.12.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
</configuration>
6.แก้ไขไฟล์ Program.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
static void Main(string[] args)
{
try
{
log.Info("*********************************");
log.Info("************* BEGIN *************");
log.Info(AppDomain.CurrentDomain.FriendlyName);
// Check AppSettings in App.config
if (!checkConfig())
{
log.Error("Missing some config");
return;
}
string connMySql = ConfigurationManager.AppSettings.Get("connMySql");
log.Info(string.Format(" '{0}'", connMySql.Split(';')[0]));
mysql.sql.ExecuteReader(mysql.qry.QuerySelectData(""));
log.Info("************** END **************");
log.Info("");
}
catch (Exception ex)
{
log.Error(ex.Message);
log.Error(ex.ToString());
}
} // end main
private static bool checkConfig()
{
string connMySql = ConfigurationManager.AppSettings.Get("connMySql");
if (string.IsNullOrEmpty(connMySql))
{
log.Error("'connMySql' not found in App.config");
return false;
}
return true;
}
} // end class
}