using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Reflection;
using KSDataInfo.utils;
namespace KSDataInfo.Models
{
public static class MySqlHelper
{
public static readonly string connStrLocal = ConfigurationManager.ConnectionStrings["MySqlConnStr"].ConnectionString;
public static List<string> GetTableNames()
{
using (MySqlConnection con = new MySqlConnection(connStrLocal))
{
con.Open();
DataTable dt = con.GetSchema("Tables");
List<string> tableName = dt.Rows.OfType<DataRow>().Select(x => (string)x["Table_Name"]).ToList();
con.Close();
return tableName;
}
}
//1.执行增、删、改的方法:ExecuteNonQuery
public static int ExecuteNonQuery(string sql, params MySqlParameter[] pms)
{
using (MySqlConnection con = new MySqlConnection(connStrLocal))
{
using (MySqlCommand cmd = new MySqlCommand(sql, con))
{
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
con.Open();
return cmd.ExecuteNonQuery();
}
}
}
//2.封装一个执行返回单个对象的方法:ExecuteScalar()
public static object ExecuteScalar(string sql, params MySqlParameter[] pms)
{
using (MySqlConnection con = new MySqlConnection(connStrLocal))
{
using (MySqlCommand cmd = new MySqlCommand(sql, con))
{
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
con.Open();
return cmd.ExecuteScalar();
}
}
}
//3.执行查询多行多列的数据的方法:ExecuteReader
public static MySqlDataReader ExecuteReader(string sql, params MySqlParameter[] pms)
{
MySqlConnection con = new MySqlConnection(connStrLocal);
using (MySqlCommand cmd = new MySqlCommand(sql, con))
{
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
try
{
con.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception)
{
con.Close();
con.Dispose();
throw;
}
}
}
//4.执行返回DataTable的方法
public static DataTable ExecuteDataTable(string sql, params MySqlParameter[] pms)
{
DataTable dt = new DataTable();
using (MySqlDataAdapter adapter = new MySqlDataAdapter(sql, connStrLocal))
{
//LogHelper.WriteLogInfo("【connstr:" + connStrLocal + ",sql:" + sql + "】");
if (pms != null)
{
adapter.SelectCommand.Parameters.AddRange(pms);
}
adapter.Fill(dt);
}
return dt;
}
public static void ExecuteSqlTran(ArrayList SQLStringList)
{
using (MySqlConnection connection = new MySqlConnection(connStrLocal))
{
connection.Open();
MySqlCommand command = new MySqlCommand
{
Connection = connection
};
MySqlTransaction transaction = connection.BeginTransaction();
command.Transaction = transaction;
try
{
for (int i = 0; i < SQLStringList.Count; i++)
{
string str = SQLStringList[i].ToString();
if (str.Trim().Length > 1)
{
command.CommandText = str;
command.ExecuteNonQuery();
}
}
transaction.Commit();
}
catch (MySqlException exception)
{
transaction.Rollback();
throw new Exception(exception.Message);
}
}
}
public static List<T> GetModel<T>(string sql, params MySqlParameter[] pms)
{
try
{
var dt = ExecuteDataTable(sql, pms);
return ToDataList<T>(dt);
}
catch (Exception ex)
{
LogHelper.WriteErrorInfo(ex);
}
return new List<T>();
}
/// <summary>
/// DataTable转成List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> ToDataList<T>(this DataTable dt)
{
var list = new List<T>();
var plist = new List<System.Reflection.PropertyInfo>(typeof(T).GetProperties());
foreach (DataRow item in dt.Rows)
{
T s = Activator.CreateInstance<T>();
for (int i = 0; i < dt.Columns.Count; i++)
{
PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
if (info != null)
{
try
{
if (!Convert.IsDBNull(item[i]))
{
object v = null;
if (info.PropertyType.ToString().Contains("System.Nullable"))
{
v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType));
}
else
{
v = Convert.ChangeType(item[i], info.PropertyType);
}
info.SetValue(s, v, null);
}
}
catch (Exception ex)
{
throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
}
}
}
list.Add(s);
}
return list;
}
}
}