简体   繁体   中英

ASP.NET C# & Stored Procedures

I am making the transition from DataTableAdapters in MSVS to creating Stored Procedures in MS SQL Server.

This is what I have so far.

protected void Submit_Click(object sender, EventArgs e)
    {
         var conString = ConfigurationManager.AppSettings["ConnectionString"].ToString(); 
         using (SqlConnection con = new SqlConnection(conString))
        {
            using (SqlCommand cmd = new SqlCommand("getAdministrators", con))
            {
                cmd.Parameters.Add("@userName", SqlDbType.VarChar).Value = userNameTB.Text;
                cmd.Parameters.Add("@password", SqlDbType.VarChar).Value = passwordTB.Text;
                cmd.CommandType = CommandType.StoredProcedure;
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                }
            }
        }
    }

I want to grab all the rows/columns and store them in a DataSet and use the values returned at my will for whatever I wish. What am I missing to accomplish this. Or if someone has an article that could help as well?

I updated the code to use using .

I think the code is slowly getting there...

This snippet works:

    public static DataSet GetAll(int id)
    {
        using (SqlConnection con = new SqlConnection(Database.ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand("sp_ContactGetAll", con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    DataSet dsData = new DataSet();
                    da.Fill(dsData);
                    return dsData;
                }
            }
        }
    }

I may be wrong, but I would expect the following to work:

using(var reader = cmd.ExecuteReader()) {
  ds.Tables[0].Load(reader);
}

(assuming you want to populate the zeroth table)

http://msdn.microsoft.com/en-us/library/9kcbe65k.aspx

I guess you missed cmd.ExecuteReader

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