2011-09-25 80 views
1

我試圖做一個簡單的用戶註冊表單有以下4個領域,如何防止SQL數據庫重複條目使用C#.NET存儲過程

  • 用戶ID(這是唯一的)
  • 用戶名(這是唯一的)
  • 密碼
  • 電子郵件

現在我能夠阻止用戶進入在重複的用戶條目Sql數據庫。但是,當用戶提供相同的用戶名/用戶名或'用戶名創建成功'時,如果用戶名/用戶名不預先存在,則想要向用戶顯示該消息可以成功顯示該帳戶'已經存在'的事件。

請提供一些C#代碼幫助(asp.net)來解決此問題。 謝謝。

+2

我_hope_認爲'密碼'被哈希和鹽漬。 – SLaks

回答

1

您可以在插入前處理檢查。

爲此,您可以使用事件(例如OnItemInserting事件與DetailsView),使用用戶輸入的值來檢查用戶名是否存在,如果是,則取消插入。您可以使用OnItemInserted事件來確認新帳戶。

你應該做額外的輸入檢查和檢查值等,但下面只是僞代碼,讓你在正確的方向。

看看這些例子 OnItemInserting http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.detailsview.iteminserting.aspx

OnItemInserted http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.detailsview.iteminserted.aspx

實施例(僞碼)

<asp:DetailsView ID="NewAccount" runat="server" 
    DataSourceID="Account" 
    AutoGenerateRows="false" 
    OnItemInserted="NewAccount_ItemInserted" 
    OnItemInserting="NewAccount_ItemInserting"> 
    <Fields> 
     <asp:BoundField DataField="UserName" HeaderText="UserName" /> 
     <asp:TemplateField HeaderText="Password"> 
      <InsertItemTemplate> 
      <%-- Put your password boxes here --%> 
      </InsertItemTemplate> 
     </asp:TemplateField> 
     <asp:BoundField DataField="Email" HeaderText="Email" /> 
    </Fields> 
    </asp:DetailsView> 

背後的代碼

void NewAccount_ItemInserted(object sender, DetailsViewInsertedEventArgs e) 
    { 
    // Account successfully inserted 
    PanelAccountSuccessful.Visible = true; // Show the successful message 

    } 

    void NewAccount_ItemInserting(object sender, DetailsViewInsertEventArgs e) 
    { 
    // Check for account that exists 
    SqlConnection .... 
    SqlDataSource .... 

    //use e.Values["key"] to compare 
    // select an account that matches e.Values["UserName"] and/or e.Values["Email"] 
    SqlDataReader reader .... 

    while (reader.read()) 
    { 
     // If you returned results then the account exists 
     PanelAccountExists.Visible = true; // Show the error message that the account exists 
     e.Cancel = true; // This cancels the insert 
    } 

    // Otherwise this will fall through and do the insert 
    // Check that the passwords match and any other input sanitation you need 
    if (Password1.Text.Trim() != Password2.Text.Trim()) 
     e.Cancel = true; // Cancel if passwords don't match 
    } 
2

無法你只是使用一個存儲過程來測試和插入用戶,並返回一個輸出參數和結果?

CREATE PROC addUser @UserID decimal, @Username varchar()..., @Result varchar(50) output 
as 
if exists(Select UserId from Users where username = @Username) 
begin 
set @Result = 'Already there' 
return 
end 

insert Users .... 
set @Result= 'Success'