• C#程序读取数据库中包含null的列的值


     private void btn2_Click(object sender, RoutedEventArgs e)
            {
                using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Test20140531;User ID=sa;Password=123"))
                {
                    conn.Open();
                    using (SqlCommand cmd2 = conn.CreateCommand())
                    {
                        cmd2.CommandText = "select * from T_Student";
                        using (SqlDataReader reader = cmd2.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                //string Name = reader.GetString(1);
                                //MessageBox.Show("姓名为:" + Name);


                                //int Age = reader.GetInt32(2);
                                //MessageBox.Show("所有人的年龄为:"+Age);


                                //long Id = reader.GetInt64(0);

                                //MessageBox.Show("Id值分别为:" + Id);

                               

           string H = reader["Hobbit"].ToString();

                                //string Hobbit = reader.GetString(3);
                                MessageBox.Show("爱好分别为:" + H);
                                
                            }
                        }
                    }
                }

            }


    参照以上代码,按取非空列的方式:

                               string Hobbt = reader.GetString(3);

                               MessageBox.Show("爱好分别为:" + Hobbit);

    在对取包含null的列的值时候,在读取到第一个null值时,程序就抛异常终止了,为了解决这个异常终止问题,我们可以用方法:

                               string H = reader["Hobbit"].ToString();

                                //string Hobbit = reader.GetString(3);
                                MessageBox.Show("爱好分别为:" + H);

    去读取含null列的值了



    其中我的数据库表结构如下:

    程序运行结果如下图:


    更多知识分享:微笑空间站

  • 相关阅读:
    bzoj:2423: [HAOI2010]最长公共子序列
    bzoj:3994:vijos1949: [SDOI2015]约数个数和
    bzoj4332;vijos1955:JSOI2012 分零食
    bzoj:1726: [Usaco2006 Nov]Roadblocks第二短路
    bzoj:1724: [Usaco2006 Nov]Fence Repair 切割木板
    bzoj:1666: [Usaco2006 Oct]Another Cow Number Game 奶牛的数字游戏
    bzoj:1230: [Usaco2008 Nov]lites 开关灯
    bzoj:1941: [Sdoi2010]Hide and Seek
    bzoj:1699;poj 3264: [Usaco2007 Jan]Balanced Lineup排队
    bzoj 1705;poj 3612:[Usaco2007 Nov]Telephone Wire 架设电话线
  • 原文地址:https://www.cnblogs.com/xuyongsky1234/p/4113571.html
Copyright © 2020-2023  润新知