2011-08-18 162 views
4

我想从表Account中选择多个(全部)值。select *只返回一个值

string query = "SELECT * FROM Account"; 
     SqlConnection connection = new SqlConnection(connectionString); 
     SqlCommand command = new SqlCommand(query, connection); 
     SqlDataReader reader; 
     connection.Open(); 
     reader = command.ExecuteReader(); 
     reader.Read(); 
     label1.Text = reader["PasswordHash"].ToString(); 
     connection.Close(); 

为什么总是只返回第一行。实际上它返回一行,因为如果我在where子句中设置类似where id = 2 and id = 3的东西,它仍然只返回一个值。 表格有超过一个值我检查表格Management Studio,有查询运行,因为他们应该。

在此先感谢。

+3

我很好奇:如果你想从结果集中读取多个行,你能指望什么label1.Text看你做的时候是怎样的? –

+0

因为您只调用'reader.Read()'一次?!?!?!?该调用读取**结果集的一行** - 就这些了。 –

+0

这只是练习,以充分掌握sql服务器的功能。标签是从最简单的事情开始。 –

回答

8

因为您没有循环查询结果,所以只显示一个结果。

string query = "SELECT * FROM Account"; 
    SqlConnection connection = new SqlConnection(connectionString); 
    SqlCommand command = new SqlCommand(query, connection); 
    SqlDataReader reader; 
    connection.Open(); 
    reader = command.ExecuteReader(); 
    While(reader.Read()) 
{ 
    label1.Text += " " +reader["PasswordHash"].ToString(); 
} 
    connection.Close(); 

上面的代码遍历查询结果,并会给你分配给label1.text一个连接字符串,想要什么。您也可以通过在while循环中插入Console.WriteLine(reader["PasswordHash"].ToString());来查看结果

2

阅读器一次只能前进一条记录。你需要通过导致循环设置为循环:

while (reader.Read()) { 
    // do something with the current row by accessing reader[] 
} 
reader.Close(); 

有更好的方法来构建你的代码,但是这说明你缺少了这一点,需要最少的变化。

1

reader.Read()将得到下一行,因此您可以使用while(reader.Read())遍历行。

3

你应该做

while (reader.Read()) 
    // process information 

您需要遍历所有检索到的信息。

旁注:在您的SqlConnection,SqlCommand和SqlDataReader上使用使用语句,以确保对象正确放置。

1

看着你的代码,我的建议是使用一些其他对象来添加代码。标签文本不是一个合适的选择。

尝试使用foreach循环导入列表以检索已返回的所有数据。

1

你需要一个while循环;

while(reader.Read()) { 
      Console.WriteLine("{0}", reader[0]); 
     } 
1

使用where id = 2 and id = 3将返回零次的结果为ID = 2和id = 3是互斥的。 where id = 2 or id = 3可以工作。

while (reader.Read()) { /*Do stuff with current row*/ } 

可以工作,通过对结果进行迭代

+0

我在想'或',但我写了'和':) –

1

你需要循环和数据读取器是你的公司的最佳途径德,样品,是这样的:

SqlDataReader myReader = myCommand.ExecuteReader(); 
// Always call Read before accessing data. 
while (myReader.Read()) { 
    Console.WriteLine(myReader.GetInt32(0) + ", " + myReader.GetString(1)); 
} 
// always call Close when done reading. 
myReader.Close();