首页 > 数据库 >C# 使用 DbDataReader 来访问数据库

C# 使用 DbDataReader 来访问数据库

时间:2024-07-17 12:51:25浏览次数:8  
标签:dataReader Name C# 数据库 List property reader DbDataReader public

C# 使用SqlDataAdapter和DataSet来访问数据库
实体

namespace VipSoft.Entity
{
    [Table(Name = "PH_Prescription")]
    public class Prescription : Web.Core.Orm.Entity
    { 
        [Column(Name = "ID")]
        public String Id {get;set;}
        
        [Column(Name = "PATIENT_NAME")]
        public String PatientName {get;set;}
    }
}

DataReader扩展类,通过反射,进行实体赋值

public static class DbDataReaderExtensions
{
    public static List<T> ToList<T>(this DbDataReader dataReader)
    {
        List<T> list = new List<T>();
        using (dataReader)
        {
            while (dataReader.Read())
            {
                T model = Activator.CreateInstance<T>();
                foreach (PropertyInfo property in model.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
                {
                    var columnAttribute = property.GetCustomAttributes(typeof(ColumnAttribute), false).FirstOrDefault() as ColumnAttribute;
                    if (!dataReader.IsDBNull(dataReader.GetOrdinal(columnAttribute.Name)))
                    {
                        Type convertTo = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
                        property.SetValue(model, Convert.ChangeType(dataReader[columnAttribute.Name], convertTo), null);
                    }
                }
                list.Add(model);
            }
        }
        return list;
    }
}

获取

public List<Prescription> GetPrescriptionList()
{
    List<Prescription> result = new List<Prescription>();
    string connectionString = "Data Source=(local);Initial Catalog=YourDatabase;Integrated Security=True";
    string sql = $@"select * from PH_Prescription o with(nolock) where o.Status=0 ";
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlDataReader reader = null;
        try
        {
            SqlCommand command = new SqlCommand(sql, connection);
            connection.Open();
            reader = command.ExecuteReader();
            result = reader.ToList<Prescription>();
        }
        catch (Exception e)
        {
            logger.Error(e, e.Message + " => " + sql);
        }
        finally
        {
            if (reader != null)
            {
                reader.Close();
            }
        }
    }
    return result;
}

标签:dataReader,Name,C#,数据库,List,property,reader,DbDataReader,public
From: https://www.cnblogs.com/vipsoft/p/18307069

相关文章

  • [BJDCTF2020]Mark loves cat(源码泄露+命令执行)
    扫描之后发现是/.git源码泄露pythonGitHack.pyhttp://56ad87c1-d8fb-463d-9480-f0fbee5176a0.node5.buuoj.cn:81/.git/之后出现源码查看index.php<?php//包含外部文件'flag.php',可能包含变量$flaginclude'flag.php';//初始化三个变量$yds="dog";//$yd......
  • 易优CMS根据aid获取文档页面链接
    使用sql等标签获取到文档信息,但是没有获取到文档页面的链接,可以使用以下方法生成。1、在根目录下\extend\function.php中创建方法:if(!function_exists('diy_get_arcurl')){/***获取前台文档的URL*@paraminteger$aid文档ID*@paraminteger......
  • iOS开发基础112-GCD
    GrandCentralDispatch(GCD)在iOS中的常见运用场景GCD是Apple提供的多线程编程技术,旨在提供高效、轻量级的方式来执行并发任务。GCD使得管理线程变得简单且提高了应用程序的性能。以下是GCD在iOS中的一些常见运用场景,并详细介绍其底层原理。1.异步任务处理场景:网络请求使用GCD......
  • ASP.NET Core-自动映射
    1.安装NuGet包AutoMapper 2.建立示例Entity、DtoEntitypublicclassUser{publiclongId{get;set;}///<summary>///账号///</summary>publicstringUserName{get;set;}///<summary>///名字//......
  • oracle Mysql PostgreSQL 数据库的对比
    oracleMysqlPostgreSQL数据库的对比HOXJUN于2018-07-1318:44:25发布阅读量7.3k收藏11点赞数1版权Mysql的多表连接查询只支持NestLoop,不支持hashjoin和sortmergejoin,子查询性能较低,不支持sequenceMysql在执行过程中出现问题只产生很少的性能数据,难准确定位......
  • Emacs的优点,用Emacs写程序真的比IDE更方便吗?
    Emacs是一个经典的文本编辑器,以其强大的扩展性和灵活性而闻名。虽然在当今的软件开发行业中,集成开发环境(IDE)如VisualStudio和IntelliJIDEA占据了主导地位,Emacs依然保持着一定的独特优势和忠实用户群。在这篇文章中,我们将探讨Emacs的主要优点,并评估在现代编程实践中,使用Emacs......
  • C语言——实验课大作业(十个C语言实验)
    第1关:实验8数学函数任务描述本关任务:编写一个能计算数的正弦、余弦、平方根的小程序。相关知识为了完成本关任务,你需要掌握:调用C语言自带的函数库的方法。导入函数相关库#include<math.h>导入相关库后,可以直接调用相关的函数进行运算,比如计算数a的平方根,可以通过调用s......
  • C# WinForm程序全局捕捉异常处理办法
    1.winform捕获全局异常staticclassProgram{///<summary>///应用程序的主入口点。///</summary>[STAThread]staticvoidMain(){//处理未捕获......
  • iOS开发基础110-Core Graphics应用场景
    CoreGraphics是一种强大的二维图形绘制框架,广泛应用于iOS开发中。以下是几个常见的运用场景以及对应的代码示例:1.自定义视图绘制通过覆盖UIView的drawRect:方法,可以自定义视图的外观。示例代码:#import<UIKit/UIKit.h>@interfaceCustomView:UIView@end@implementat......
  • 【2024-ZR-C Day 1】数论基础
    1.Ex-GCD1.1.定义若\((a,b)=1\),则必然存在整数\(x\)使得\(ax\equiv1(\bmodb)\).即:\(ax+by=\gcd(a,b)\),\(x,y\)必然有解。1.2.裴蜀定理推论:若\((a,b)=1\),则必然存在整数\(x,y\)满足\(ax+by=1\).裴蜀定理:对于\(a,b\in\mathbb{Z}\),\(\existsx,......