1

我想检查用户名是否已经存在。这是我已经达到的,但它不起作用。

 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
4

1 回答 1

1
  1. 您对SQL-Injection开放。不要将字符串连接到 sql-query 但使用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 
于 2012-12-20T10:52:42.767 回答