C# 执行MySQL查询并返回List泛型
本次 查询方法的引用 其中部分需要去NuGet包管理器中安装包,不会安装包的在网上搜一下安装方法很简单,这里就不详细说明了,以下是本次方法所添加的引用。
using Dapper;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Configuration;
using MySql.Data.MySqlClient;
本次查询SQL方法的主体
查询MySQL并返回List<T>
的使用,其中T为数据库字段实体模型.
/// <summary>
/// 执行sql并返回List泛型
/// </summary>
/// <typeparam name="T">模型</typeparam>
/// <param name="files">查询字段</param>
/// <param name="table">表名</param>
/// <param name="where">条件</param>
/// <param name="_object">object</param>
/// <returns></returns>
public static List<T> ExecuteQueryToList <T>(string files, string table, string where, object _object)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat(@"SELECT {0} FROM {1} where {2};", files, tableName, where);
MySqlConnection connection = new MySqlConnection(ConnectionString);
try
{
connection.Open();
List<T> data = connection.Query<T>(sb.ToString(), _object).ToList<T>();
return data;
}
catch
{
throw;
}
finally
{
connection.Close();
}
}
创建一个表格
下面举一个简单的示例(假设表名为UserTable,下图为表结构):
字段 | 类型 |
---|---|
Id | int |
Name | string |
Age | int |
Sex | string |
以下为表中数据
Id | Name | Age | Sex |
---|---|---|---|
1 | 张三 | 12 | 男 |
2 | 李四 | 13 | 女 |
3 | 王五 | 14 | 男 |
创建Model
/// <summary>
///
/// </summary>
[Table("UserTable")]
public class UserModel
{
/// <summary>
/// 主键Id
/// </summary>
[Key]
public int Id { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; }
/// <summary>
/// 性别
/// </summary>
public string Sex { get; set; }
}
调用查询方法
List<UserModel> List = MySQLHelper.QueryToList<UserModel>("*","UserTable","1=1", null);
以上便是一个最基本的查询,如果有查询条件,加上查询条件即可;
【注】: 如有侵权联系删除