C# 从数据库中读取每行的值

C# 从数据库中读取每行的值,c#,ado.net,C#,Ado.net,我正在使用ADO,并使用CreateCommand和CommandText编写和运行SQL命令,如果在SQL server中运行该命令,它将返回一些行。但是在C中,如何运行它并循环它返回的行的值呢?它在SQL server中只返回一列,但例如,在C中,我需要80行来读取这些行的值,并用它们进行一些处理。如果您有一个名为cmd的SqlCommand,并且您的SqlConnection名为connection: 如果您有一个名为cmd的SqlCommand,并且您的SqlConnection名为co

我正在使用ADO,并使用CreateCommand和CommandText编写和运行SQL命令,如果在SQL server中运行该命令,它将返回一些行。但是在C中,如何运行它并循环它返回的行的值呢?它在SQL server中只返回一列,但例如,在C中,我需要80行来读取这些行的值,并用它们进行一些处理。

如果您有一个名为cmd的SqlCommand,并且您的SqlConnection名为connection:

如果您有一个名为cmd的SqlCommand,并且您的SqlConnection名为connection,则ExecuteReader将返回一个

ExecuteReader返回一个

它在SQL server中只返回一列,但例如,返回80行

问题:您只读取了一次值[可能使用ifreader.Read]

解决方案:您需要读取这些值,直到。Read方法使用whilereader.Read返回false

试试这个:

List<string> strNames=new List<string>();
using(SqlConnection con = new SqlConnection("connection string here"))
using(SqlCommand command = new SqlCommand("select Name from mytable",con))
{    
   con.Open();
   SqlDataReader reader = command.ExecuteReader();
   while (reader.Read())
   {
     strNames.Add(reader["Name"]);
   }
}
它在SQL server中只返回一列,但例如,返回80行

问题:您只读取了一次值[可能使用ifreader.Read]

解决方案:您需要读取这些值,直到。Read方法使用whilereader.Read返回false

试试这个:

List<string> strNames=new List<string>();
using(SqlConnection con = new SqlConnection("connection string here"))
using(SqlCommand command = new SqlCommand("select Name from mytable",con))
{    
   con.Open();
   SqlDataReader reader = command.ExecuteReader();
   while (reader.Read())
   {
     strNames.Add(reader["Name"]);
   }
}
看看这个: 当您处于WhilerReader.Read循环中时,您可以访问这些值

看看这个: 当您处于WhilerReader.Read循环中时,您可以访问这些值