C# orm mysql_转:C#制作ORM映射学习笔记三 ORM映射实现

这个博客介绍了如何使用C#实现ORM(对象关系映射)来操作MySQL数据库,包括打开和关闭数据库连接、执行SQL命令、查询单个记录、查询多个记录以及更新和插入数据的操作。
摘要由CSDN通过智能技术生成

usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Data;usingSystem.Data.Common;usingSystem.Data.SQLite;usingSystem.Reflection;usingMySql.Data;usingMySql.Data.MySqlClient;namespaceORM

{public classDbAccess

{privateDbConnection dbConnection;privateDbCommand dbCommand;privateDbDataReader reader;//打开数据库连接

public voidOpenDB()

{try{switch(DbConfig.Type)

{case DbType.Sqlite: dbConnection = new SQLiteConnection("data source =" + DbConfig.Host); break;case DbType.Mysql: dbConnection = new MySqlConnection(DbConfig.Host); break;default: break;

}

dbConnection.Open();

}catch(Exception e)

{throwe;

}

}//关闭数据库连接

public voidCloseSqlConnection()

{if (dbCommand != null)

{

dbCommand.Dispose();

}

dbCommand= null;if (reader != null)

{

reader.Dispose();

}

reader= null;if (dbConnection != null && dbConnection.State ==ConnectionState.Open)

{

dbConnection.Close();

dbConnection.Dispose();

}

dbConnection= null;

}//执行Sql命令

public int ExecuteQuery(stringsql)

{

OpenDB();

dbCommand=dbConnection.CreateCommand();

dbCommand.CommandText=sql;

reader=dbCommand.ExecuteReader();returnreader.RecordsAffected;

}//查询符合条件的第一个记录

public T FirstOrDefault(Sql sql)

{try{

ExecuteQuery(sql.GetSql());

T result= default(T);if(reader.Read())

{

Type type= typeof(T);if (type.IsPrimitive || type == typeof(string) || type == typeof(DateTime) ||type.IsEnum)

{if(type.IsEnum)

{

result= (T)Enum.ToObject(type, reader.GetValue(0));

}else{

result= (T)Convert.ChangeType(reader.GetValue(0), type);

}

}else{

result= Activator.Crea

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值