简体   繁体   中英

get Record from DB using stored procedure in c#

I'm trying to fetch a record from the database using a stored procedure, but it returns null in SqlDataReader object.

Here is my code:

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

You need to call dr.Read() before accessing the data! Also: put your disposable objects ( SqlConnection , SqlCommand , SqlDataReader ) into using(..) { ... } blocks to ensure proper disposal:

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

Also: what do you do if your stored procedure returns multiple rows of data? You need to somehow deal with that, too

如果我没记错的话,您会错过dr.Read()来获取第一条记录。

HasRows is simply telling you whether or not there are any rows to read, whereas Read() advances the internal cursor to the next row in the data, and incidentally returns False if there are no more rows to read, or True if there was another row available. We need dr.read()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM