使用c#中的存储过程从DB获取记录

时间:2015-11-27 11:44:24

标签: c# sql-server stored-procedures

我尝试使用存储过程从数据库中获取记录,但它会在null对象中返回SqlDataReader

这是我的代码:

public Buybest_Liberary.Data.UserManagement getUser(string email)
{
    Buybest_Liberary.Data.UserManagement obj = new Buybest_Liberary.Data.UserManagement();
    string conString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\ahmadshair\Documents\Buybest.mdf;Integrated Security=True;Connect Timeout=30";

    SqlConnection connection = new SqlConnection(conString);
    connection.Open();

    SqlCommand _cmd = new SqlCommand("getUserRecord", connection);
    _cmd.CommandType = CommandType.StoredProcedure;
    _cmd.Parameters.Add("@Email", SqlDbType.NVarChar).Value = email;

    SqlDataReader dr = _cmd.ExecuteReader();

    if (dr.HasRows)
    {
        obj.UId = Convert.ToInt32(dr[0]);
        obj.Email = dr[1].ToString();
        obj.Password = dr[2].ToString();
    }

    return obj;
} 

3 个答案:

答案 0 :(得分:5)

在访问数据之前,您需要致电dr.Read()!另外:将您的一次性物品(SqlConnectionSqlCommandSqlDataReader)放入using(..) { ... }块,以确保妥善处置:

public Buybest_Liberary.Data.UserManagement getUser(string email)
{
    Buybest_Liberary.Data.UserManagement obj = new Buybest_Liberary.Data.UserManagement();

    // You should read the connection string from a config file 
    // don't specify it explicitly in code!
    string conString = ConfigurationManager.ConnectionStrings["-your-connection-string-name-here-"].ConnectionString;

    using (SqlConnection connection = new SqlConnection(conString))
    using (SqlCommand _cmd = new SqlCommand("getUserRecord", connection))
    {
        _cmd.CommandType = CommandType.StoredProcedure;
        _cmd.Parameters.Add("@Email", SqlDbType.NVarChar).Value = email;

        connection.Open();

        using (SqlDataReader dr = _cmd.ExecuteReader())
        { 
            // the SqlDataReader could return *multiple* rows - how are you
            // going to deal with that? Create an object for each row of data
            // and add them to a list to return? 
            while (dr.Read())
            {
                 obj.UId = Convert.ToInt32(dr[0]);
                 obj.Email = dr[1].ToString();
                 obj.Password = dr[2].ToString();
            }

            dr.Close();
        }

        connection.Close();
    }

    return obj;
} 

另外:如果您的存储过程返回多个行数据,您会怎么做?你也需要以某种方式解决这个问题

答案 1 :(得分:4)

如果我没弄错的话,你错过了一个dr.Read()来获取第一条记录。

答案 2 :(得分:2)

HasRows只是告诉你是否有任何行要读取,而Read()将内部游标推进到数据的下一行,如果没有更多行要读取,则顺便返回False,如果没有,则返回True还有另一排可用。 我们需要dr.read()