namespace Connection.DataBaseServer
{
public class MySQL
{
protected string Server { get; set; }
protected string User { get; set; }
protected string Pass { get; set; }
protected string DbName { get; set; }
protected int TimeOut { get; set; }
public MySQL(string server, string user, string pass, string dbname, int timeout)
{
this.Server = server;
this.User = user;
this.Pass = pass;
this.DbName = dbname;
this.TimeOut = timeout;
}
public void ExecuteNonQuery(string query)
{
ExecuteNonQuery(query, null);
}
public void ExecuteNonQuery(string query, Dictionary<string, object> param)
{
using (MySqlConnection con = new MySqlConnection(GenerateConnectionString()))
{
con.Open();
using (MySqlCommand cmd = new MySqlCommand(query, con))
{
FillParams(cmd, param);
cmd.ExecuteNonQuery();
}
}
}
public int CountDataTable(DataTable dt, string query)
{
return CountDataTable(dt, query, null);
}
public int CountDataTable(DataTable dt, string query, Dictionary<string, object> param)
{
using (MySqlDataAdapter adap = new MySqlDataAdapter(query, GenerateConnectionString()))
{
FillParams(adap.SelectCommand, param);
adap.Fill(dt);
return dt.Rows.Count;
}
}
public void FillDataTable(DataTable dt, string query, Dictionary<string, object> param)
{
using (MySqlDataAdapter adap = new MySqlDataAdapter(query, GenerateConnectionString()))
{
FillParams(adap.SelectCommand, param);
}
}
public void UpdateDataTable(DataTable dt, MySqlDataAdapter adap, Dictionary<string, object> param)
{
MySqlCommandBuilder cmdBuilder = new MySqlCommandBuilder(adap);
FillParams(cmdBuilder.GetUpdateCommand(), param);
adap.Update(dt);
}
protected virtual string GenerateConnectionString()
{
MySqlConnectionStringBuilder csb = new MySqlConnectionStringBuilder();
csb.Server = Server;
csb.UserID = User;
csb.Password = Pass;
csb.Database = DbName;
csb.ConnectionTimeout = (uint)TimeOut;
return csb.ToString();
}
protected void FillParams(MySqlCommand cmd, Dictionary<string, object> param)
{
if (param == null)
return;
foreach (var keyvalue in param)
{
cmd.Parameters.AddWithValue(keyvalue.Key, keyvalue.Value);
}
}
}
}