索引超出范围,数据行数少于6行

5q4ezhmt  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(335)

我需要什么和我目前拥有什么的小简报
我连接到一个数据库,从中获取数据,然后得到(name,longnumber),基本上我有一个事件(action),在事件发生时触发(这个操作也给我一个longnumber)。
我需要比较从事件(action)得到的longNumber和从数据库得到的longNumber,如果它们相似,我就取名称并使用它。例如hello,alex(alex取自数据库)
问题
我得到的索引超出了范围,使用我的逻辑,所有的文本都会改变,我想要实现的是,将文本改为获得长数字的人的名字,与事件中的长数字相同
代码:从数据库获取数据

using UnityEngine;
using System.Collections;
using MySql.Data.MySqlClient;
using System;
using System.Linq;
using System.Collections.Generic;

public class MySqlTestScript : MonoBehaviour
{

private static MySqlTestScript _instnace;
public static MySqlTestScript sharedInstance()
{
    return _instnace;
}

string row = "";

public string host = "*****";
public string database = "*******";
public string usrename= "*******";
public string password = "******";

public List<Data> userData = new List<Data>();

 Data data;

void Awake()
{
    _instnace = this;
}

// Use this for initialization
public void Start()
{

    GetDataFromDatabase();
}

public string GetDataFromDatabase()
{
     string myConnectionString = "Server="+host+";Database="+database+";Uid="+usrename+ ";Pwd="+password+";";

    MySqlConnection connection = new MySqlConnection(myConnectionString);
    MySqlCommand command = connection.CreateCommand();
    command.CommandText = "SELECT * FROM Users";
    MySqlDataReader Reader;
    try
    {
        connection.Open();
        Reader = command.ExecuteReader();

        while (Reader.Read())
        {

            for (int i = 0; i < Reader.FieldCount; i++)
            {
                //rfid_tags.Add (Reader.GetString("UserName"));
                //rfid_tags.Add(Reader.GetString("RFID_Tag"));
                data = new Data(Reader.GetString("UserName"), Reader.GetString("RFID_Tag"));
                userData.Add(data);
                // ws.DomainUrl = reader.GetString("DomainUrl");
                // rfid_tags.Add(Reader.GetValue(i).ToString() + ",");
                // row += Reader.GetValue(i).ToString() + ", ";
            }

            Debug.Log(row);
        }
    }

    catch (Exception x)
    {
        Debug.Log(x.Message);
        return x.Message;
    }

    connection.Close();
    return row;

}

}

public class Data {

public string username { get; set; }
public string rfid { get; set; }

public Data(string _name, string _rfid)
{
    username = _name;
    rfid = _rfid;
}

public void SetUserName(string _userName) { username = _userName; }
public void SetRFID(string _rfid) { rfid = _rfid; }

}

用于比较事件(操作)中的值并显示文本的代码

void OnTagsReported(ImpinjReader sender, TagReport report)
{
    Debug.Log("OnTagsReported");

   // This event handler is called asynchronously 
    // when tag reports are available.
    // Loop through each tag in the report 
    // and print the data.
     foreach (Tag tag in report)
    {

        Debug.Log(tag.Epc);
    //    Debug.Log(MySqlTestScript.sharedInstance().rfid_tags[0]);

            Debug.Log("STEP ONE");
            for (int i = 0; i < MySqlTestScript.sharedInstance().userData.Count; i++)
            {
                Debug.Log("STEP TWO");
                if (tag.Epc.ToString().Trim() == MySqlTestScript.sharedInstance().userData[i].rfid)
                {
                    Debug.Log("STEP THREE");
                    // TODO References the Name 
                    Loom.QueueOnMainThread(() => {

                         namesTxt[i].text = MySqlTestScript.sharedInstance().userData[i].username;

                    });

                }
            }

正如您在事件脚本中看到的,它非常不灵活,如果我的数据库少于6行,它会给出超出范围的索引。我需要使它更友好和通用
任何帮助都将不胜感激,我希望我的问题是明确的谢谢:)!

33qvvth1

33qvvth11#

解决这个问题的一种方法是把你的每一个箱子都包在另一个箱子里 if 语句来检查数据库是否有那么多行

if (MySqlTestScript.sharedInstance().longNumbers.Length > 1) {
    if (tag.Epc.ToString().Trim() == MySqlTestScript.sharedInstance().longNumbers[0].ToString()) {

        if(MySqlTestScript.sharedInstance().userNames[0] != null)
           txt1.text = "Hello "+ MySqlTestScript.sharedInstance().userNames[0];
        }
    }
}
else {
    txt1.text = "";
}

这将避免索引超出范围异常。在每种 Package 情况下,您都需要将比较增加到1、2、3等。
这不是最漂亮的解决办法,但可以避免例外。另一种选择是用try-catch块 Package 。又不是最漂亮的,但能完成任务。

h4cxqtbf

h4cxqtbf2#

这应该更有意义:
数据库:

using UnityEngine;
using System.Collections;
using MySql.Data.MySqlClient;
using System;
using System.Linq;
using System.Collections.Generic;

public class MySqlTestScript : MonoBehaviour
{

private static MySqlTestScript _instnace;
public static MySqlTestScript sharedInstance()
{
    return _instnace;
}

string row = "";

public string host = "*****";
public string database = "*******";
public string usrename= "*******";
public string password = "******";

public List<AppUser> users = new List<AppUser>();

void Awake()
{
    _instnace = this;
}

// Use this for initialization
public void Start()
{

    GetDataFromDatabase();
}

public string GetDataFromDatabase()
{
  string myConnectionString = "Server=" + host + ";Database=" + database + ";Uid=" + usrename + ";Pwd=" + password + ";";

  MySqlConnection connection = new MySqlConnection(myConnectionString);
  MySqlCommand command = connection.CreateCommand();
  command.CommandText = "SELECT * FROM users";
  MySqlDataReader Reader;

  try
  {
    connection.Open();
    Reader = command.ExecuteReader();

    while (Reader.Read())
    {
      users.Add(new AppUser() { 
        username = Reader.GetString("UserName").Trim(),
        rfid = Reader.GetString("longNumbers ").Trim()
      });
    }
  }
  catch (Exception x)
  {
    Debug.Log(x.Message);
    return x.Message;
  }

  connection.Close();
  return row;
}
}

数据对象:

public Class AppUser 
{ 
  public string rfid { get; set; } 
  public string username { get; set; } 
}

事件/数据比较:

void OnTagsReported(ImpinjReader sender, TagReport report)
{
  Debug.Log("OnTagsReported");

  // This event handler is called asynchronously 
  // when tag reports are available.
  // Loop through each tag in the report 
  // and print the data.
  foreach (Tag tag in report)
  {
    Debug.Log(tag.Epc);
    List<AppUser> appUsers = MySqlTestScript.sharedInstance().users;
    int numUsers = appUsers.Count;
    Debug.Log(numUsers);

    for (int i = 0; i < numUsers; i++)
    {
      if (tag.Epc.ToString().Trim() == appUsers[i].rfid)
      {
        // TODO References the Name 
        Loom.QueueOnMainThread(() => {
          if (i < namesTxt.Count) namesTxt[i].Text = appUsers[i].username; //assumes textnames is a "List" of textboxes and is already populated with instances of text1, text2 text3 etc. The if is just to guard against there being more rows in the DB than textboxes
        });
      }
    }
  }
}

相关问题