使用MySqlReader从数据库获取数据时出错始终返回Null

时间:2014-07-11 10:29:17

标签: c# database wcf mysqlconnection

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

1 个答案:

答案 0 :(得分:0)

试试这个

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