如何从数据库读取整行到c#?

时间:2018-04-25 20:26:51

标签: c# sql-server ado.net

我们假设以下代码返回整个结果行:

using (SqlCommand cmdMessages = new SqlCommand("SELECT * FROM Email where Sender = @usernameLog", conn))
{
    cmdMessages.Parameters.Add(new SqlParameter("@usernameLog", Sender));

    using (SqlDataReader reader = cmdMessages.ExecuteReader())
    {
        while (reader.Read())
        {
            Console.Write(); // Receiver's Name which comes from database
            Console.Write();// The message which comes from same row as the receiver's name
        }
    }
}

查询在SQL Server中正常工作。

SQL Server的输出:

 User      hi   

我希望在控制台中拥有相同的输出。

2 个答案:

答案 0 :(得分:1)

获取所需的列值:

while (reader.Read())
        {
               reader.GetString(1);
               reader.Getstring(2);
         }

or
reader.GetString("ColumnName1");
reader.GetString("ColumnName2");

答案 1 :(得分:1)

如果您只想在迭代datareader时显示正在重新搜索的值,则可以执行以下操作:

using (SqlCommand cmdMessages = new SqlCommand("SELECT * FROM Email where Sender = @usernameLog", conn))
{
     cmdMessages.Parameters.Add(new SqlParameter("@usernameLog", Sender));
     using (SqlDataReader reader = cmdMessages.ExecuteReader())
     {
         int count = reader.FieldCount;
         while (reader.Read())
         {
             for(int i = 0 ; i < count ; i++) 
             {
                  Console.WriteLine(reader.GetValue(i));
             }
         }
     }
}

使用int count = reader.FieldCount;计算您要返回的字段数。然后,您将使用for语句进行迭代。

如果您只想显示2个值,则只需将for替换为: Console.WriteLine(reader.GetValue(0) + " " + reader.GetValue(1));