SQL选择查询同一属性的多个值 [英] SQL Select query of more than one value of a same Attribute

查看:564
本文介绍了SQL选择查询同一属性的多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含许多属性的Sql数据库。从那里我想在一个名为getQuestion的数组中获取question属性的所有值。这是我的代码

I have a Sql Database with many attributes. From there i want to take all the value of question attribute in an array named getQuestion Here Is my code

vcon.Open();
  SqlCommand cmd = new SqlCommand("select question from examQuestion where tchId='123'", vcon);
  SqlDataReader dr = cmd.ExecuteReader();
  String[] getQuestion = { "" };
  int i = 0;

  while (dr.Read())
  {
      getQuestion[i] = dr.GetString(0);
      i++;
  }
  vcon.Close();



当数据库包含单个值时,它很好,但是当数据库有多个值时,它提供错误索引超出了数组的范围 。问题是什么?请帮我。我是ASP.Net的新手。


It is fine when database contain single value, But when database has more then one value it provide an Error "Index was outside the bounds of the array". What is the problem? Please Help me. I am very new at ASP.Net.

推荐答案

试试这种方式:

Try this way:
vcon.Open();
SqlCommand cmd = new SqlCommand("select question from examQuestion where tchId='123'", vcon);
SqlDataReader dr = cmd.ExecuteReader();
ArrayList getQuestion = new ArrayList();
int i = 0;

while (dr.Read())
{ 
    getQuestion.Add((string)dr["question"]);//or getQuestion.Add((string)dr[0]);
}
vcon.Close();


使用Generic List轻松的方式

use Generic List the Easy way
vcon.Open();
          SqlCommand cmd = new SqlCommand("select question from examQuestion where tchId='123'", vcon);
          SqlDataReader dr = cmd.ExecuteReader();
           System.Collections.Generic.List<string> LstQuestion = new System.Collections.Generic.List<string>();

          while (dr.Read())
          {
              LstQuestion.Add(dr.GetString(0));

          }
          vcon.Close();


这篇关于SQL选择查询同一属性的多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆