2012-12-20 27 views
1

我想檢查用戶名是否已經存在。這是我已經達到的,但它不工作。如何在signUp時檢查已存在的用戶名

Dim cmdstr As String = "Select count(*) from Registration where username = '" & txtName.Text & "'" 
Dim userExist As SqlCommand = New SqlCommand(cmdstr, con) 
Dim temp As Integer = Convert.ToInt32(userExist.ExecuteScalar().ToString()) 
    If (temp = 1) Then 
     Response.Write("user name is already Exist!!") 
    End If 
+1

** SQL INJECTION **,去查找它。什麼是錯誤或爲什麼「不起作用」? –

+0

它不會給我的信息 – Hassan

回答

1
  1. 你打開SQL-Injection。不要連接字符串的SQL查詢,但使用SqlParameters
  2. 您還沒有開通連接(我認爲)

這裏有一個完整的示例:

Public Shared Function GetUserCount(userName As String) As Int32 
    Const sql = "SELECT COUNT(*) FROM Registration where username = @UserName" 
    Using con As New SqlConnection(connectionString) 
     Using cmd = New SqlCommand(sql, con) 
      cmd.Parameters.AddWithValue("@UserName", userName) 
      con.Open() 
      Using reader = cmd.ExecuteReader() 
       If reader.HasRows 
        reader.Read() 
        Dim count As Int32 = reader.GetInt32(0) 
        Return count 
       End If 
      End Using 
     End Using 
    End Using 
End Function 

和使用方法這樣:

Dim userCount As Int32 = GetUserCount(txtName.Text.Trim()) 
If userCount > 0 
    LblWarning.Text = "User-name already exists!" 
End If 
+0

謝謝。我試了一下,但它給了我這個錯誤「 當數據不存在時無效嘗試讀取。」 這裏指的是「count As Int32 = reader.GetInt32(0)」 – Hassan

+0

@Hassan:編輯我的回答,你應該首先使用'reader.HasRows'屬性。 –

+0

魅力,感謝蒂姆億次:) 你救了我^ _ ^ – Hassan

相關問題