First, a few important recommendations:
Do not use SELECT *
. You might get back something different than what you thought (e.g. if the database schema has been changed in the meantime). Instead, specify each column that you're interested in explicitly.
Instead of glueing together a SQL query using string concatenation, use a @parameterized
query. This is a good principle to follow for reasons of both performance (query caching) and safety (preventing SQL injection attacks).
So your code becomes:
cmd.CommandText = "SELECT Player1, Player2 FROM Game WHERE gameID = @gameId";
cmd.Parameters.AddWithValue("@gameId", game_id);
Now to your question: How to receive the values of Player1
and Player2
of each record? That is where IDataReader
s come in. A data reader is a forward-only cursor over the resulting table that allows you to access the values of each returned record:
// 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
}
}