1

I created a function which checks if an username already exists in DB. I am using SqlCommand with sql-parameterd to avoid Sql-Injection. To execute I should use the class SqlAccess, because the whole existing project is built with that.

The Code I've written...

'Check if username already exists'
Public Shared Function usernameExists(Username As String) As Boolean
    Dim sqlCommand As SqlCommand = New SqlCommand("Select UserLogin From [User] where UserLogin = '@Username'")
    Dim param As SqlParameter = New SqlParameter("Username", SqlDbType.VarChar)
    param.Value = Username
    sqlCommand.Parameters.Add(param)

Try
    SQLAccess.OpenSQLConnection(sqlCommand, SetDBConnectionData) 'SqlDBConnectionData is a function which returns a structSQlAccess'
    Dim dsUsers As DataSet = SQLAccess.SQLQueryToDS(sqlCommand)

    If dsUsers.Tables(0).Rows.Count > 0 Then
        Return True
    Else
        Return False
    End If
Catch ex As Exception
    Return True 'TODO - Error Mgs
End Try

End Function

But it doesn't work, the DataSet does not contain rows. Could anyone please show me how to do it properly?

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
kk-dev11
  • 2,654
  • 5
  • 37
  • 48

1 Answers1

2

Don't put the parameter in apostrophes as here:

"Select UserLogin From [User] where UserLogin = '@Username'"

but as here:

"Select UserLogin From [User] where UserLogin = @Username"

Also, i assume that SQLAccess is a custom class which manages the connection. I would strongly advise against such a helper class in ASP.NET since it's just a source of nasty errors, all the more if your connection is Shared:

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 1
    Thank you. Your solution works. You're right. It's a very old project. We should consider rebuilding it. Thank you very much for your input and suggestion. It was very helpful. – kk-dev11 Apr 10 '14 at 09:30