Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexOutOfRangeException while trying to select on database by C#

sorry if this sounds noobish. I'm trying to make a Quiz game on Unity by using C# and a database in SQL Server. In this part, i'm trying to show the highest score so, i did a code to select the max in database:

  public bool BuscarScoreFinal1()
    {
        SqlDataReader dataReader = null;

        if (RunQuery(string.Format("SELECT MAX (PlayerScore1) FROM ScoreQuiz1", tableScoreQuiz1), ref dataReader))
        {
            while (dataReader.Read())
            {
                id1 = dataReader.GetInt32(dataReader.GetOrdinal("ID"));
                PlayerName1 = dataReader.GetString(dataReader.GetOrdinal("PlayerName1"));
                PlayerScore1 = dataReader.GetInt32(dataReader.GetOrdinal("PlayerScore1"));

                break;
            }
        }

        if (dataReader != null) dataReader.Close();

        return true;
    }

Then, i try to print the data in a UI text in this script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UpdateScore : MonoBehaviour
{

    public GameObject Question3Display;
    public Text yourText;
    public bool Buscardados13;

    // Use this for initialization
    void Start()
    {
        Buscardados13 = GameObject.Find("DatabaseConnection").GetComponent<DatabaseInterface>().Connect() == true;
        Buscardados13 = GameObject.Find("DatabaseConnection").GetComponent<DatabaseInterface>().BuscarScoreFinal1() == true;
        yourText.text = Question3Display.GetComponent<DatabaseInterface>().PlayerScore1.ToString();
    }

    // Update is called once per frame
    void Update()
    {

    }
}

And it gives me this error:

IndexOutOfRangeException: ID System.Data.ProviderBase.BasicFieldNameLookup.GetOrdinal (System.String fieldName) (at <8012ff544f1c4cb384c200861f770215>:0) System.Data.SqlClient.SqlDataReader.GetOrdinal (System.String name) (at <8012ff544f1c4cb384c200861f770215>:0) DatabaseInterface.BuscarScoreFinal1 () (at Assets/Scripts/DatabaseInterface.cs:621) UpdateScore.Start () (at Assets/Scripts/UpdateScore.cs:17)

I think this error is not a problem of connection of selecting the wrong table because, if i try a different query (for example, just a simple select) it works without errors. I don't think i wrote the query bad because it works in SQL Server. Here's the table i'm trying to access;

Here's a screenshot of the table i'm using

like image 563
FRP72 Avatar asked Feb 09 '19 14:02

FRP72


1 Answers

I can only speculate -- because you don't show data -- but I'm pretty sure you want:

SELECT TOP (1) Id, PlayerName1, PlayerScore1
FROM ScoreQuiz1
ORDER BY PlayerScore1 DESC;

You can't really access columns that aren't included in the SELECT.

like image 52
Gordon Linoff Avatar answered Nov 17 '22 11:11

Gordon Linoff