Create Procedure Spaddshoppingcart @user_id varchar (50), @title_id varchar (6)
As declare @title varchar (80), @Price Money
IF exists (SELECT * from shoppingcart where title_id = @ Title_ID)
/ * If you purchased this book, direct update quantity * / begin update shoppingcart set quantity = quantity 1 where title_id = @ title_id end
ELSE / * If you have not purchased this book, add ShoppingCart * / begin / * get book name and price * / select @ title = Title, @ price = price from titles where title_id = @title_id / * Add book to shopPingCart * / Insert INTO ShoppingCart (User_ID, Title_ID, Title, Quantity, Price) VALUES (@ user_id, @ title_id, @ title, 1, @ price) endGO
Key code: private void addorder () {
SqlConnection CN = New SqlConnection ((String) ConfigurationSettings.AppSettings ["NetBooksDB"]);
// Specify stored procedure SqlCommand cmd = new SqlCommand (); cmd.Connection = cn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "spAddShoppingCart"; // set parameters user_id cmd.Parameters.Add ( "@ user_id ", Sqldbtype.varchar, 50) .value = context.user.Identity.Name;
// Set the title_id parameter NameValueCollection QS = Request.QueryString; cmd.parameters.add ("@ title_id", sqldbtype.varchar, 6) .value = qs.get ("Title_ID");
Try {cn.open (); cmd.executenonQuery (); cn.close ();
Response.Redirect ("ShoppingCart.aspx");
Catch (system.data.sqlclient.sqlexception e) {if (e.Number! = 0) {lblmsg.style ["color"] = "red"; lblmsg.text = "Error:" "[" E. Number.toString () "]" e.tostring ();}}