gpt4 book ai didi

c# - 尝试通过 C# 在数据库上进行选择时出现 IndexOutOfRangeException

转载 作者:太空狗 更新时间:2023-10-29 23:04:58 25 4
gpt4 key购买 nike

抱歉,如果这听起来很笨拙。我正在尝试通过使用 C# 和 SQL Server 中的数据库在 Unity 上制作测验游戏。在这部分,我试图显示最高分,所以我做了一个代码来选择数据库中的最大值:

  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;
}

然后,我尝试在此脚本中的 UI 文本中打印数据:

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()
{

}
}

它给了我这个错误:

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)

我认为这个错误不是选择错误表的连接问题,因为如果我尝试不同的查询(例如,只是一个简单的选择)它可以正常工作而不会出错。我不认为我写的查询不好,因为它在 SQL Server 中工作。这是我要访问的表;

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

最佳答案

我只能推测——因为你没有显示数据——但我很确定你想要:

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

您无法真正访问未包含在 SELECT 中的列。

关于c# - 尝试通过 C# 在数据库上进行选择时出现 IndexOutOfRangeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54607445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com