• C#中DBNull问题


    当数据库中一个字段不是必填项时,在往数据库中插入数据的时候往往会插入一个空字符串就草草了事了。在这里用DBNull可以解决这个问题

    /// <summary>
            /// 插入数据
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void button2_Click(object sender, RoutedEventArgs e)
            {
                string name = txtName.Text;
                string age = txtAge.Text;
                string height = txtHeight.Text;
                object objName;
                if (name.Length <= 0)
                {
                    objName = DBNull.Value;
                }
                else
                {
                    objName = name;
                }
                object objAge;
                if (age.Length <= 0)
                {
                    objAge = DBNull.Value;
                }
                else
                {
                    objAge = age;
                }
                object objHeight;
                if (height.Length <= 0)
                {
                    objHeight = DBNull.Value;
                }
                else
                {
                    objHeight = height;
                }
                SqlHelper.ExecuteNonQuery(@"insert into T_Person(Name,Age,Height) values (@Name,@Age,@Height)",
                    new SqlParameter("@Name", objName),
                    new SqlParameter("@Age", objAge),
                    new SqlParameter("@Height", objHeight));
            }
            /// <summary>
            /// 读出数据
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void button3_Click(object sender, RoutedEventArgs e)
            {
                DataSet ds = SqlHelper.ExecuteDataSet("select * from T_Person where id=2");
    
                string name;
                if (ds.Tables[0].Rows[0]["Name"] == DBNull.Value)
                {
                    name = null;
                }
                else
                {
                    name = ds.Tables[0].Rows[0]["Name"].ToString();
                }
                int? age;
                if (ds.Tables[0].Rows[0]["Age"] == DBNull.Value)
                {
                    age = null;
                }
                else
                {
                    age = int.Parse(ds.Tables[0].Rows[0]["Age"].ToString());
                }
                txtName.Text = name;
                txtAge.Text = age.ToString();
                txtHeight.Text=ds.Tables[0].Rows[0]["Height"].ToString();
            }

  • 相关阅读:
    网络爬虫基础练习
    中文词频统计
    综合练习:英文词频统计
    字符串、组合数据类型练习
    MVC Controller进行单元测试
    mvc、webapi杂记
    C#异步执行
    cross-domain-ajax-request-jquery
    JS将/Date(1446704778000)/转换成string
    SQL并发数查询
  • 原文地址:https://www.cnblogs.com/hp-discuz/p/5132720.html
Copyright © 2020-2023  润新知