【问题标题】:Error while fetching data from database using MySqlReader Always Return Null使用 MySqlReader 从数据库中获取数据时出错总是返回 Null
【发布时间】:2014-07-11 10:29:17
【问题描述】:
public Employee getDetails(string sUid) 
{
    Employee employee = new Employee();
    //List<string> list = new List<string>();
    string strConnection = "Server=10.47.4.68;Database=empdb;Uid=root;Pwd=root;";
    using (MySqlConnection con = new MySqlConnection(strConnection))
    {
        con.Open();
        MySqlCommand cmd = new MySqlCommand("SELECT name FROM signup where uid=@uid", con);
        cmd.Parameters.AddWithValue("@uid", sUid);
        MySqlDataReader reader = cmd.ExecuteReader();
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                employee.uid = reader.GetString(reader.GetOrdinal("uid"));
                employee.Name = reader.GetString(reader.GetOrdinal("name"));
                employee.dob = reader.GetString(reader.GetOrdinal("dob"));
                employee.work_loc = reader.GetString(reader.GetOrdinal("work_loc"));
                employee.mobile = reader.GetString(reader.GetOrdinal("mobile"));
            }
            // closing the connection pool
            reader.Close();
            con.Close();

        }
        else 
        {
            return null;
        }
        return employee;
    }
}

【问题讨论】:

  • 也添加错误信息。
  • 你做了什么诊断?如果没有行,这将返回 null,例如...

标签: c# database wcf mysqlconnection


【解决方案1】:

试试这个

    if (reader.Read())
    {
        employee.uid = reader.GetString(reader.GetOrdinal("uid"));
        employee.Name = reader.GetString(reader.GetOrdinal("name"));
        employee.dob = reader.GetString(reader.GetOrdinal("dob"));
        employee.work_loc = reader.GetString(reader.GetOrdinal("work_loc"));
        employee.mobile = reader.GetString(reader.GetOrdinal("mobile"));

        // closing the connection pool
        reader.Close();
        con.Close();
        return employee;
    }
    else 
    {
        return null;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 2021-07-30
    • 2013-09-11
    • 2017-04-06
    • 1970-01-01
    • 2019-07-10
    相关资源
    最近更新 更多