C# 使用 DbDataReader 来访问数据库
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;
}
本文来自博客园,作者:VipSoft 转载请注明原文链接:https://www.cnblogs.com/vipsoft/p/18307069
分类:
C#
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
2023-07-17 bat cmd 无效参数/选项 - deleting
2012-07-17 ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'mysql'
2012-07-17 ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)