C#反射在資料庫連線時的應用
反射的應用
1.查詢指定ID的資料
//查詢指定id的資料,返回指定的物件
private T FindData<T>(int id)
{
Type ty = typeof(T);
//在這裡建立例項物件的時候不能轉成指定的型別,只能是Object物件
//轉成指定型別後面就賦值不成功
// T t=(T)Activator.CreateInstance(ty);
//原來我是這麼寫的,也能建立例項物件,但後面怎麼賦值都不行,全是NULL,
//特別要注意這點,要賦值完後才轉成指定的型別
object obj = Activator.CreateInstance(ty);
string sql = $"select * from [{ty.Name}] where ID={id}";
OleDbConnection conn = new OleDbConnection(connString);
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
dr.Read();
foreach (var v in ty.GetFields())
{
if(v.FieldType.FullName=="System.Int32") //在這判斷欄位型別,我這隻有兩種型別int,string,如果型別多就要多寫幾種判斷
{
obj.GetType().GetField($"{v.Name}").SetValue(obj, int.Parse(dr[$"{v.Name}"].ToString())); //第一種方法賦值
}
else
{
ty.GetField(name: $"{v.Name}").SetValue(obj, dr[$"{v.Name}"].ToString()); //第二種方法賦值
}
}
dr.Close();
conn.Close();
//var vname = obj.GetType().GetField("mAge");
//vname.SetValue(obj, 23);
//賦值完了才轉成指定的型別
return (T)obj;
}
2.新增資料到資料庫中
private bool Insert_Into<T>(T t)
{
int nRet = 0;
string intoSql = null;
string fileName = null;
string fileValue = null;
List<OleDbParameter> parList = new List<OleDbParameter>();
Type ty = t.GetType();
foreach (System.Reflection.FieldInfo v in ty.GetFields())
{
fileName += v.Name + ",";
fileValue += $"@{v.Name},";
OleDbParameter par = new OleDbParameter($"@{v.Name}", v.GetValue(t));
parList.Add(par);
}
fileName = fileName.Substring(0, fileName.Length - 1);
fileValue = fileValue.Substring(0, fileValue.Length - 1);
intoSql = $"INSERT INTO [{ty.Name}] ({fileName}) VALUES ({fileValue})";
using (OleDbConnection conn = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand(intoSql, conn))
{
cmd.Parameters.Clear();
cmd.Parameters.AddRange(parList.ToArray());
conn.Open();
nRet = cmd.ExecuteNonQuery();
conn.Close();
}
}
return nRet == 1;
}
3.修改資料
private bool UpdateData<T>(int id,T t)
{
int nRet = 0;
string intoSql = null;
string fileName = null;
List<OleDbParameter> parList = new List<OleDbParameter>();
Type ty = t.GetType();
foreach (System.Reflection.FieldInfo v in ty.GetFields())
{
fileName += v.Name + $"=@{v.Name},";
OleDbParameter par = new OleDbParameter($"@{v.Name}", v.GetValue(t));
parList.Add(par);
}
fileName = fileName.Substring(0, fileName.Length - 1);
intoSql = $"UPDATE [{ty.Name}] SET {fileName} WHERE ID={id}";
using (OleDbConnection conn = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand(intoSql, conn))
{
cmd.Parameters.Clear();
cmd.Parameters.AddRange(parList.ToArray());
conn.Open();
nRet = cmd.ExecuteNonQuery();
conn.Close();
}
}
return nRet == 1;
}
4.刪除資料
private bool DeleteData<T>(int id)
{
int nRet = 0;
string intoSql = null;
Type ty = typeof(T);
intoSql = $"DELETE FROM [{ty.Name}] WHERE ID={id}";
using (OleDbConnection conn = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand(intoSql, conn))
{
conn.Open();
nRet = cmd.ExecuteNonQuery();
conn.Close();
}
}
return nRet == 1;
}
5.讀取所有資料,返回一個所有資料的表
private DataTable GetDataTable<T>()
{
DataTable dt = new DataTable();
Type ty = typeof(T);
string sql = $"SELECT * FROM [{ty.Name}]";
using (OleDbConnection conn = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
conn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
}
conn.Close();
}
return dt;
}
簽名:GreenLeaf1976