zoukankan      html  css  js  c++  java
  • 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列的值了



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

    程序运行结果如下图:


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

  • 相关阅读:
    Python requests“Max retries exceeded with url” error
    命令行链接mongo、redis、mysql
    python 删除字典某个key(键)及对应值
    python标准模块(二)
    python标准模块(一)
    格式化输出
    LeetCode----1. Two Sum
    文件操作(初阶)
    python函数基础
    python3内置函数
  • 原文地址:https://www.cnblogs.com/xuyongsky1234/p/4113571.html
Copyright © 2011-2022 走看看