首先,一些重要的建议:
所以你的代码变成:
cmd.CommandText = "SELECT Player1, Player2 FROM Game WHERE gameID = @gameId";
cmd.Parameters.AddWithValue("@gameId", game_id);
现在回答您的问题:如何接收每条记录的值Player1
和值?Player2
这就是IDataReader
s 的用武之地。数据读取器是结果表上的只进游标,它允许您访问每个返回记录的值:
// SqlConnection connection = cmd.Connection;
connection.Open();
using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
int player1Index = reader.GetOrdinal("Player1");
int player2Index = reader.GetOrdinal("Player2");
while (reader.Read()) // one loop iteration per record returned from SELECT
{
string player1 = cmd.GetString(player1Index);
string player2 = cmd.GetString(player2Index);
… // do something with player1, and player2
}
}