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