I’m trying to check whether a Username and Password exist in my MySQL database and if so I need to return true, otherwise false. This is what I have atm:
myconn.Open()
Dim selectSQL As String = "SELECT *
FROM member
WHERE Username = " & objMember.Username & "
AND Password= " & objMember.Password
Dim cmd As New OdbcCommand(selectSQL, myconn)
cmd.ExecuteNonQuery()
If cmd.Parameters.Count = 1 Then
Return True
Else
Return False
End If
myconn.Close()
myconn.Dispose()
All I get is 0, even though the Username and Password exist! Or perhaps I’m wrong with my coding?
SOLUTION
myconn.Open()
Dim count As Integer = 0
Dim selectSQL As String = "SELECT COUNT(*)
FROM member
WHERE Username = ?
AND Password= ?"
Dim cmd As New OdbcCommand(selectSQL, myconn)
cmd.Parameters.AddWithValue("LidLoginnaam", objLid.LidLoginnaam)
cmd.Parameters.AddWithValue("LidWachtwoord", objLid.LidWachtwoord)
count = Convert.ToInt32(cmd.ExecuteScalar())
If count = 1 Then
Return True
Else
Return False
End If
myconn.Close()
myconn.Dispose()
Do not use string concatenation to build your SQL queries, use parameters instead.
http://msdn.microsoft.com/en-us/library/system.data.odbc.odbcparameter.aspx
If you don’t use the data retrieved from your query, then just use ExecuteScalar to get the number of records that matched your Username and Password.
http://msdn.microsoft.com/en-us/library/system.data.odbc.odbccommand.executescalar.aspx
This basically returns TRUE if count > 0 (meaning there is a record that matched the Username and Password).
Also check out the distinction between the different command execution methods here: http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand(v=vs.71).aspx. You are using ExecuteNonQuery for retrieving records which is incorrect for this purpose.
Hope this helps.