C# 查询MySQL返回List<T>

本次 查询方法的引用 其中部分需要去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,下图为表结构):

字段类型
Idint
Namestring
Ageint
Sexstring

以下为表中数据

IdNameAgeSex
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);

以上便是一个最基本的查询,如果有查询条件,加上查询条件即可;

【注】: 如有侵权联系删除

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值