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);
        }
View Code
复制代码

 

posted @   不买南孚电池  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示