【发布时间】:2016-01-24 17:53:46
【问题描述】:
我正在 Unity 中创建一个游戏,允许用户输入 SQL 命令。
假设我的 SQL 数据库中有一个名为 Terminals 的表,其中包含 Id、Name、Type 和 Hacked 列。
如果用户输入一个 SELECT 命令,例如SELECT Id, Name FROM Terminals;,那么 lineList 会添加返回的数据字段的数量,例如仅限 ID 和名称。
我的问题是,如何将 Terminals 类中的属性分配给从 SQL 查询返回的正确值?
这是我的代码:
public class SQLConnect : MonoBehaviour {
private void Query(string sqlCommand)
{
using (dbCon = new SqlConnection(connectionString))
{
using (dbcmd = dbCon.CreateCommand())
{
dbcmd.CommandText = sqlCommand;
dbCon.Open();
using (reader = dbcmd.ExecuteReader())
{
var readList = new List<List<object>>();
while (reader.Read())
{
var lineList = new List<object>();
for (int i = 0; i < reader.FieldCount; i++)
{
lineList.Add(reader.GetValue(i)); // This reads the entries in a row
}
readList.Add(lineList);
}
}
}
}
}
}
public static class SQLDynamicData
{
public static List<Terminals> TerminalList;
public class Terminals
{
public int Id { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public bool Hacked { get; set; }
public Terminals(int id, string name, string type, bool hacked)
{
Id = id;
Name = name;
Type = type;
Hacked = hacked;
}
}
}
这是我尝试过的:
using (reader = dbcmd.ExecuteReader())
{
var readList = new List<List<object>>();
while (reader.Read())
{
var lineList = new List<object>();
for (int i = 0; i < reader.FieldCount; i++)
{
lineList.Add(reader.GetValue(i)); // This reads the entries in a row
}
readList.Add(lineList);
}
foreach (var item in readList)
{
SQLDynamicData.TerminalList.Add(new SQLDynamicData.Terminals(Convert.ToInt32(item[0]), item[1].ToString(), item[2].ToString(), Convert.ToBoolean(item[3])));
}
}
这样做的问题是,很明显如果返回的数据只是 Id 和 Name,那么 item[2] 和 item[3] 会抛出异常。此外,如果用户只选择 Name 而不是其他,则可能首先返回 Name 而不是 Id,在这种情况下,将 item[0] 转换为 int 是不正确的
我该怎么做?我需要这样做,因为我想根据 SQL 数据更新我的游戏内对象。
【问题讨论】: