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();
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM