reader.Read() only read once even when there are multiple rows to read

試著忘記壹切 提交于 2019-12-12 02:53:11

问题


I have the code

while (reader.Read())
{
    if (reader[incrementer]!=DBNull.Value){
        string playerToInform = reader.GetString(incrementer).ToString();
        string informClientMessage = "ULG=" + clientIP + ","; //User Left Game
        byte[] informClientsMessage = new byte[informClientMessage.Length];
        informClientsMessage = Encoding.ASCII.GetBytes(informClientMessage);
        playerEndPoint = new IPEndPoint(IPAddress.Parse(playerToInform), 8001);
        clientSocket.SendTo(informClientsMessage, playerEndPoint);
    }
    incrementer++;
}

which after debugging my code i see contains 4 entries. However only the first result is ever read from the reader. After the first iteration to find if the result returned is null or not the loop starts again and immediately finishes even though there are three more rows to read.

Any ideas as to why this may be occuring would be apprechiated.

edit - this is the reader i used

OleDbDataReader reader = dBConn.DataSelect("SELECT player1_IP, player2_IP, player3_IP, player4_IP FROM running_games WHERE game_name = '" + gameName + "'", updateGameList);

回答1:


You're incrementing "incrementer" as if that was the row number, but a DataReader holds only one row per Read() and the indexing is for the field number.

Use this:

while (reader.Read())
{
    for(int colNum = 0; colNum < 4; colNum++)
    {
        if (reader[colNum]!=DBNull.Value)
        {
            string playerToInform = reader.GetString(colNum).ToString();
            string informClientMessage = "ULG=" + clientIP + ","; //User Left Game
            byte[] informClientsMessage = new byte[informClientMessage.Length];
            informClientsMessage = Encoding.ASCII.GetBytes(informClientMessage);
            playerEndPoint = new IPEndPoint(IPAddress.Parse(playerToInform), 8001);
            clientSocket.SendTo(informClientsMessage, playerEndPoint);
        }
    }
}



回答2:


The indexer of DbDataReader (DataReader is something else) or a database specific subclass, returns the value of the specified (by index or name).

While DbDataReader.Read() moves to the next row.

If you want to apply the same logic to multiple columns you need to loop over the columns, and the rows:

while (db.Read()) {

  for (var colIdx = 0; colIdx < columnCount. ++colIdx) {
    if (!db.IsDbNll(colIdx)) {
      string value = db.GetString(colIdx);
      // Process value
    }
  }

}



回答3:


Incrementer is unnecessary. reader.Read() advances to next record and returns false if there are no more rows.

Check documentation on msdn



来源:https://stackoverflow.com/questions/36475901/reader-read-only-read-once-even-when-there-are-multiple-rows-to-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!