首页 > 解决方案 > C#读取MySql int字段返回错误数字

问题描述

我正在使用 C# MVC5 & MySQL 编写一个网页,当我从 int 字段请求一个数字时,MySQL 总是返回一个错误的数字,我找不到一些解决方案。

MySQL 喜欢:

| Id | Type | Level | Parent_id |ChildrenCount |
| 1  | T    | 1     | 1         |3             |
| 2  | SC   | 2     | 1         |2             |
| 3  | SH   | 3     | 2         |1             |
| 4  | TK   | 4     | 3         |0             |
...

我可以sql正常显示它们。

但是C#不能。

下面是 C# 代码。

public Item GetItem(int id, int level, int pos)
{
    Item item = new Item { Id = -1 };

    using (MySqlConnection con = new DBConnect().MySql())
    {
        string sql = $"SELECT * FROM item WHERE Parent_id={id} AND Level={level} LIMIT {pos}, 1;";
        using (MySqlCommand cmd = new MySqlCommand(sql, con))
        {
            con.Open();
            MySqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                item.Id = reader.GetInt32(0);
                item.Type = reader.GetString(1);
                item.Level = reader.GetInt32(2);
                item.ChildrenCount = reader.GetInt32(3);
            };
        }
    }
    return item;
}
public void GetItemList(int id, int level, int count, ref List<Item> pli, int initPos=0)
{
    int pos = 0;
    pos += initPos;
    Item item = GetItem(id, level, pos);

    if (item.Id == -1)
    {
        return;
    }

    pli.Add(item);

    // Here item.Level is wrong.

    if (pli.Count() < count)
    {
        if (item.ChildrenCount > 0)
        {
            int ChildPos = 0;
            int newLevel = item.Level + 1;
            GetItemList(item.Id, newLevel, count, ref pli, ChildPos);
        }
        else
        {
            int newPos = pos + 1;
            GetItemList(id, level, count, ref pli, newPos);
        }
    }
}

来电

public List<Item> GetInitItem(int id)
{
    List<Item> resItemList = new List<Item> { };
    GetItemList(id, level: 1, count: 50, pli: ref resItemList, initPos: 0);

    return resItemList;
}

其他信息都可以,只有Level列错误,全部返回1。

这是页面的结果:

ID:6133   Type:T   Level:1   Count:744   
ID:6154   Type:SC   Level:1   Count:67 

标签: c#mysqlasp.net-mvc

解决方案


推荐阅读