C# Sql多字段插入(反射!)

public bool Insert(object obj) { Type type = obj.GetType(); PropertyInfo[] properties = type.GetProperties(); string[] col = new string[properties.Length ]; string[] par = new string[properties.Length ]; string[] value = new string[properties.Length ]; int count = 0; foreach (var item in properties) { if (item.Name!=null) { col[count] = item.Name; par[count] = "@"+item.Name; if (item.GetValue(obj) != null) { value[count] = item.GetValue(obj).ToString(); } else { value[count] = "-"; } count++; } } string cols= string.Join(",", col); string parm = string.Join(",", par); string insert = "insert into wbgzd (" + cols + ") values ("+ parm +")"; SqlParameter[] sqls = new SqlParameter[par.Count()]; for (int i = 0; i < par.Count(); i++) { sqls[i] = new SqlParameter(par[i], value[i]); }; Console.WriteLine(insert); return true; } private void button1_Click(object sender, EventArgs e) { wbgzd wbgzd = new wbgzd(); Type type = wbgzd.GetType(); PropertyInfo[] properties = type.GetProperties(); foreach (var item in this.panel1.Controls) { if (item as TextBox!=null) { foreach (var item2 in properties) { if (item2.Name.ToString()== (item as TextBox).Tag.ToString()) { if ((item as TextBox).Text=="") { MessageBox.Show((item as TextBox).Name.ToString() + "不能为空!"); return; } else { item2.SetValue(wbgzd, (item as TextBox).Text.ToString()); } } } } } Console.WriteLine(wbgzd.gzID); Insert(wbgzd); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构