c#一步一步實現ORM(二)mysql
上一篇描述了簡單的思路,這一片咱們來稍微細化一下sql
1插入的時候忽略某些字段c#
public int Insert<T>(T o, params string[] except) { //有時候咱們添加的時候只想添加部分字段,或者有的字段是自增的方式,那麼要去掉這個字段(在sqlserver裏面是這樣,在mysql裏面 是插入 null) try { Type type = typeof(T); var tablename = "dbo.[" + typeof(T).Name + "]"; string fields = ""; string values = ""; List<SqlParameter> paras = new List<SqlParameter>(); object v = null; foreach (var item in type.GetProperties()) { bool flag = true; if (except != null && except.Contains(item.Name)) { flag = false; } if (flag) { v = item.GetValue(o, null); if (v != null) { fields += "," + "[" + item.Name + "]"; values += ",@" + item.Name; paras.Add(new SqlParameter("@" + item.Name, v)); } } } string sql = string.Format("insert into {0} ({1}) values({2})", tablename, fields.Substring(1), values.Substring(1)); return ExcuteSql(sql, paras); } catch (Exception e) { Console.Write(e.ToString()); return 0; } }
2批量插入sqlserver
public int InsertArray<T>(IEnumerable<object> o, params string[] except) { if (o.Count() == 0) { return 0; } Type type = typeof(T); var tablename = "dbo.[" + typeof(T).Name + "]"; List<SqlParameter> paras = new List<SqlParameter>(); string sql = ""; int count = 0; foreach (var i in o) { count++; string fields = ""; string values = ""; //object v = null; foreach (var item in type.GetProperties()) { bool flag = false; if (!flag) { var vitem = item.GetValue(i, null); if (vitem != null) { fields += ",[" + item.Name + "]"; values += ",@" + count + item.Name; paras.Add(new SqlParameter("@" + count + item.Name, vitem)); } } } sql += string.Format("insert into {0} ({1}) values({2});", tablename, fields.Substring(1), values.Substring(1)); } return ExcuteSql(sql, paras); }
private int ExcuteSql(string sql, IEnumerable<SqlParameter> paras) { using (SqlConnection conn = new SqlConnection(this.sqlConnStr)) { SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = sql; cmd.Parameters.AddRange(paras.ToArray()); conn.Open(); int flag = 0; try { flag = cmd.ExecuteNonQuery(); } catch (Exception e) { throw e; } conn.Close(); return flag; } }
下一篇咱們開始學習修改,刪除,和解析lambda表達式學習