asp.net 如何給使用者傳參
asp.net和資料庫的互動太多,如果把語句都寫在程式碼裡面,看起來太長太亂。我更喜歡在資料庫裡面把操作過程維護成過程或者函式,在程式碼裡面一呼叫就可以了。這可能是我剛入門程式設計的一種錯誤的看法`~`。
1. 在資料庫建立過程.
CREATE PROC sp_UserRegister @strUserName VARCHAR(50), @strPassWord VARCHAR(50), @strRealName VARCHAR(20), @strPhone VARCHAR(20), @strAddress VARCHAR(100), @strSex VARCHAR(2) AS /******************************************* * 2010-10-25:建立,用於使用者註冊介面 *******************************************/ BEGIN IF EXISTS (SELECT 1 FROM [User] AS u(NOLOCK) WHERE u.UserName = @strUserName ) BEGIN RETURN -1 END INSERT INTO [User] ( UserName, [Password], Sex, RealName, TelePhone, [Address] ) VALUES ( @strUserName, @strPassWord, @strSex, @strRealName, @strPhone, @strAddress ) RETURN 1 END
2.asp.net中程式碼呼叫(直接把引數值寫入到資料庫)
(1)程式碼:
string strUserName = this.txtUserName.Text; string strPassWord = this.txtPassWord.Text; string strRealName = this.txtRealName.Text; string strPhone = this.txtPhone.Text; string strAddress = this.txtAddress.Text; string strSex = "";
if (rdoMale.Checked) strSex = "男";
if (rdoFemale.Checked) strSex = "女";
string strRegister = "exec sp_UserRegister '" + strUserName + "', '" + strPassWord + "', '" + strRealName + "', '" + strPhone + "', '" + strAddress + "', '" + strSex + "'"; int intReturn = DataBase.ExecuteSql(strRegister);
if (intReturn == -1) { System.Web.HttpContext.Current.Response.Write("<script>alert('該使用者名稱已經存在');</script>"); } else { System.Web.HttpContext.Current.Response.Write("<script>alert('註冊成功。');</script>"); }
(2)執行程式碼跟蹤資料庫:
exec sp_UserRegister 'dd', 'dd', 'dogdog', 'dogdog', 'dogdog', '男'