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インジェクションのためのあなたのオープン。文字列を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 に答える