C# MySQL 执行原生sql
public class MySqlHelper
{
private YourContext _context;
public MySqlHelper(YourContext context)
{
_context = context;
}
/// <summary>
/// 查询列表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql"></param>
/// <returns></returns>
public List<T> QueryForDatable<T>(string sql)
{
string conn= _context.Database.Connection.ConnectionString;
using(var connection= new MySqlConnection(conn))
{
MySqlCommand cmd = new MySqlCommand(sql, connection);
//需要open才能执行Command
connection.Open();
using (MySqlDataReader reader = cmd.ExecuteReader())
{
List<T> data = DataReaderMapToList<T>(reader);
connection.Close();
return data;
}
}
}
/// <summary>
/// 查询数量
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public int QueryForCount(string sql)
{
string conn = _context.Database.Connection.ConnectionString;
using (var connection = new MySqlConnection(conn))
{
MySqlCommand cmd = new MySqlCommand(sql, connection);
connection.Open();
//只取第一行第一个结果
Object result = cmd.ExecuteScalar();
if (result != null)
{
int count = int.Parse(result.ToString());
connection.Close();
return count;
}
connection.Close();
return 0;
}
}
public static List<T> DataReaderMapToList<T>(IDataReader dr)
{
List<T> list = new List<T>();
T obj = default(T);
List<string> columnNames = new List<string>();
//查询DataReader里面的列名集合
for (var f = 0; f < dr.FieldCount; f++)
{
columnNames.Add(dr.GetName(f));
}
while (dr.Read())
{
obj = Activator.CreateInstance<T>();
foreach (PropertyInfo prop in obj.GetType().GetProperties())
{
//判断列名是否存在
var columnName = columnNames.Find(x => x == prop.Name);
if (!string.IsNullOrEmpty(columnName))
{
prop.SetValue(obj, dr[prop.Name]);
}
}
list.Add(obj);
}
return list;
}
}
学习技术最好的文档就是【官方文档】,没有之一。
还有学习资料【Microsoft Learn】、【CSharp Learn】、【My Note】。
如果,你认为阅读这篇博客让你有些收获,不妨点击一下右下角的【推荐】按钮。
如果,你希望更容易地发现我的新博客,不妨点击一下【关注】。