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
Dim count as Integer = 0
Try
Dim sql As String = "SELECT COUNT(*) FROM member WHERE Username = #username AND Password = #password"
Dim cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#username", objMember.Username)
cmd.Parameters.AddWithValue("#password", objMember.Password)
count = Convert.ToInt32(cmd.ExecuteScalar())
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Return (count > 0)
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.
Ignoring the SQL Injection risks, strings in SQL need to be within single quotes:
Dim selectSQL As String = "SELECT m.*
FROM MEMBER m
WHERE m.username = '" & objMember.Username & "'
AND m.password = '" & objMember.Password & "' "
From a performance perspective, if you aren't interested in the contents of the query then don't return more information than you need to:
Dim selectSQL As String = "SELECT 1
FROM MEMBER m
WHERE m.username = '" & objMember.Username & "'
AND m.password = '" & objMember.Password & "' "
The query will be faster -- if any of the MEMBER columns are BLOB, you could be waiting for a while.
I think you're missing the single quotation in the query:
Dim selectSQL As String = "SELECT *
FROM member
WHERE Username = '" & objMember.Username & "'
AND Password= '" & objMember.Password & "'"
OdbcCommand's Parameter property is used for accessing the collection of parameters to be used when executing a query (more info). It doesn't help you find out how many rows are contained in the query's result set.
If your only concern is determining whether or not the requested member is in the database, change the start of your query to SELECT COUNT(*) FROM..... This revised query will return a single value indicating how many records match your query's criteria.
Execute this query by calling ExecuteScalar. The return value of this method will be the value returned by the above query--the number of rows matching your query's criteria. If the value equals zero, you know that no matching member exists in the database. Use this value instead of "cmd.Parameters.Count" in your "if" statement.
Hope this helps,
Ben
Related
I am using vb6, and the database is mysql. There is this table called "absen", it has a field called "tglabsen" which storing dates in this format : dd/mm/yyyy. I tried to find records according to the date.
eg. find records who have dates between 01/01/2017 to 01/02/2017
My question is how to store the number in a variable, and then display it in a textbox? What I tried so far, I tested this :
number = "Select count(*) from absen where tglabsen >='" & DTPicker1 & "' and tglabsen <='" & DTPicker2 & "'"
KON.Execute number
txtjumlahabsen = number
But the textbox (txtjumlahabsen) is just showing the sql query above.
KON.Execute just executes the sql statement you stored in your number variable. It doesn't update the variable with the data, which is why your textbox is showing the sql statement.
You need to open a recordset to retrieve the data:
Dim rs as New Recordset
Dim countVal as Integer
number = "Select count(*) from absen where tglabsen >='" & DTPicker1 & "' and tglabsen <='" & DTPicker2 & "'"
rs.Open number, KON, adOpenForwardOnly, adLockReadOnly
If Not rs.EOF then
countVal = rs(0).Value
End If
rs.Close
txtjumlahabsen.Text = countVal
If your sql statement is successful, the value from count(*) will be applied to the countVal variable. If it is not successful, countVal will remain at zero.
I am looking for any advice on how i can read a single column in excel that contains 500 user_id's and query a database to display results in a WPF application. A user can own or rent so the SQL would look like;
SELECT * FROM users WHERE own= 'user_id' or rent= 'user_id'
This is fine for one user but i want to read each user_id and concatenate it to the SQL statement to pull out all results from the database. Any one have any easy way of doing this?
Replace the range as necessary, credit to brettdj on the join - Simple VBA array join not working
Sub test()
Dim strQuery As String
Dim strVals As String
Dim rngTarget As Range
Set rntTarget = Range("A1:A7")
Dim varArr
Dim lngRow As Long
Dim myArray()
varArr = rntTarget.Value2
ReDim myArray(1 To UBound(varArr, 1))
For lngRow = 1 To UBound(varArr, 1)
myArray(lngRow) = varArr(lngRow, 1)
Next
strVals = "('" & Join$(myArray, "','") & "') "
strQuery = "SELECT * FROM users WHERE own in " _
& strVals & "or rent in " & strVals
End Sub
VBA noob here (as of this mourning),
In MS Access I wrote a test function to find the value of a record base on some criteria you pass in.
The function seems to work fine except in cases where there is a lookup in the column that I am searching.
Basically it might return "19" and 19 corresponds to some other table value.
It seems that the RowSource of the column is what Im after so I can do a second query to find the true value.
Can someone point me in the right direction on finding the RowSource assuming I know the column name and then utilizing it to find the value Im after?
Edit: It seems that Im not explaining myself clearly, Here is a picture of what I trying to get programatically
Try this -- I think I finally understand why you are looking for the RowSource -- sorry I didn't "get" it at first. The field you're trying to pull is a foreign key into a description table.
This function should work as a general solution for all such fields (assuming the RowSource always has the primary key first, and the description second). If there is no RowSource, it will just pull the value of the field.
It's based on your original code, rather than the changes proposed by #ron, but it should set you in the right direction. You should fix it to make it parameterized, and allow for variant data types, as ron suggests (+1 ron)
As an aside, use the ampersand (&) to join strings together in VBA to avoid things like this: abc = "1" + 1, where abc is now equal to 2 instead of "11" as you would expect if both items were intended to be strings.
Public Function lookUpColumnValue(Database As Database, column As String, table As String, lookUpColumn As String, lookUpValue As String) As String
Dim sql As String
Dim recordSet As DAO.recordSet
Dim result As String
lookUpColumnValue = "" 'Return a blank string if no result
On Error Resume Next
sql = "SELECT [" & table & "].[" & column & "] FROM [" & table & "] WHERE [" & table & "].[" & lookUpColumn & "] = '" & lookUpValue & "'"
Set recordSet = Database.OpenRecordset(sql)
If Not recordSet.EOF Then
Dim td As DAO.TableDef
'this gives your number - say, 19
result = recordSet(column)
Set td = Database.TableDefs(table)
'Get the rowsource
Dim p As DAO.Property
For Each p In td.Fields(column).Properties
If p.Name = "RowSource" Then
RowSource = Replace(td.Fields(column).Properties("RowSource"), ";", "")
Exit For
End If
Next
If Not RowSource = "" Then
Dim rs2 As DAO.recordSet
Dim qd As DAO.QueryDef
Set qd = Database.CreateQueryDef("", RowSource)
Set rs2 = Database.OpenRecordset(RowSource)
If rs2.EOF Then Exit Function
PKField = rs2.Fields(0).Name
rs2.Close
qd.Close
sql = "SELECT * FROM (" & RowSource & ") WHERE [" & PKField & "]=[KeyField?]"
Set qd = Database.CreateQueryDef("", sql)
qd.Parameters("KeyField?").Value = result
Set rs2 = qd.OpenRecordset()
If Not rs2.EOF Then
'NOTE: This assumes your RowSource *always* has ID first, description 2nd. This should usually be the case.
lookUpColumnValue = rs2.Fields(1)
End If
Else
'Return the field value if there is no RowSource
lookUpColumnValue = recordSet.Fields(column)
End If
End If
End Function
If I understand your question correctly, I think using a parameter query will solve your problem. Using parameters is good practice since they will perform implicit data type casts and also prevent injection attacks.
Notice in the following function, I changed the lookupValue to a Variant type, which allows you to pass any type of value to the function.
Public Function lookUpColumnValue( _
database As DAO.database, _
column As String, _
table As String, _
lookUpColumn As String, _
lookUpValue As Variant) As String
Dim sql As String
Dim recordSet As DAO.recordSet
Dim result As String
Dim qd As QueryDef
Set qd = database.CreateQueryDef("")
sql = "SELECT [" + table + "].[" + column + "] FROM [" + table + "] " & _
"WHERE [" + table + "].[" + lookUpColumn + "] = [parm1];"
qd.sql = sql
qd.Parameters![parm1] = lookUpValue
Set recordSet = qd.OpenRecordset()
result = recordSet(column)
EDIT
lookUpColumnValue = DLookup("Space Use Description", "Space Use Codes", result)
End Function
i hope you can help me. Fist of all, sorry if my English is annoying, i'm not a native speaker.
I'm getting this error and i can't see what i'm doing wrong. I have a program that fills a local MySQL DB with data from another program that uses an OLEB DB.
So it compares the tables and upload new data on demand. But i'm getting this error with only one table using the same Sub that i used with other tables.
Unknown column 'lpedidos.serie' in 'field list'
The problem is that 'lpedidos.serie' exists indeed. So here is the code of the sub, please don't laugh, i know that maybe is extremely inefficient, but i'm just a noob.
Public Sub notIndexedTables(table As DataTable, table2 As DataTable, tableNA As String)
Dim temptable As DataTable
temptable = table.Clone
Dim tablename As String = temptable.TableName
Dim myAdapter As MySql.Data.MySqlClient.MySqlDataAdapter
Dim SQL As String
Dim newconn As New MySql.Data.MySqlClient.MySqlConnection
newconn = mysqlConnection()
newconn.Open()
SQL = "TRUNCATE " & tableNA
myAdapter = New MySql.Data.MySqlClient.MySqlDataAdapter()
Dim command As MySql.Data.MySqlClient.MySqlCommand
command = New MySql.Data.MySqlClient.MySqlCommand(SQL, newconn)
myAdapter.DeleteCommand = command
myAdapter.DeleteCommand.ExecuteNonQuery()
For Each row As DataRow In table.Rows()
Dim columnNumber As Int32 = row.ItemArray.Count
Dim i As Integer = 0
Dim s1 As String = "("
For Each columna In row.ItemArray
i = i + 1
If i = columnNumber Then
s1 = s1 + CStr(table2.Columns.Item(i - 1).ColumnName) & ")"
Else
s1 = s1 & CStr(table2.Columns.Item(i - 1).ColumnName) & ", "
End If
Next
Dim s2 As String = "("
i = 0
For i = 0 To (columnNumber - 2)
s2 = s2 & "'" & CStr(row.Item(i)) & "', "
Next
s2 = s2 & "'" & CStr(row.Item(columnNumber - 1)) & "')"
SQL = "INSERT INTO " & tableNA & " " & s1 & " VALUES " & s2
myAdapter = New MySql.Data.MySqlClient.MySqlDataAdapter()
' myCommand = New MySql.Data.MySqlClient.MySqlCommandBuilder(myAdapter)
command = New MySql.Data.MySqlClient.MySqlCommand(SQL, newconn)
myAdapter.InsertCommand = command
myAdapter.InsertCommand.ExecuteNonQuery()
Next
newconn.Close()
newconn.Dispose()
End Sub
Basically it takes the MySQL table (tableNA), truncates it (this procedure is for tables with no index, there is other procedure for tables with unique index) and fills it with the data from the OLEB table (table) and takes the column names from the temporal copy of the MySQL table (table2) (maybe there is no need to use the table2 in this case... but anyway).
Here is the exception and the value that SQL string takes when the exception is thrown.
And here is a screenshot of the table structure in phpMyAdmin.
When you declare the New MySqlConnection you need to put the connection string in there and specify the database name. Can you show your connection string?
Dim myConnection As New MySqlConnection(myConnString)
myConnection.Open()
If that doesn't solve the problem, then try another column name and make sure it isn't a reserved keyword.
I am developing an enrolment system. But i am receiving this error: You tried to execute a query that does not include the specified expression..
I am using the following code:
Private Function RefreshAdvisoryList()
Dim vRS As New ADODB.Recordset
Dim sSQL As String
'clear list
txtsection.Clear
'On Error GoTo ReleaseAndExit
sSQL = "SELECT tblSection.SectionID, tblSection.SectionTitle, tblAdviser.SchoolYear, tblDepartment.DepartmentTitle, tblYearLevel.YearLevelTitle, tblAdviser.TeacherID" & _
" FROM (tblDepartment INNER JOIN (tblYearLevel INNER JOIN tblSection ON tblYearLevel.YearLevelID = tblSection.YearLevelID) ON tblDepartment.DepartmentID = tblSection.DepartmentID) INNER JOIN tblAdviser ON (tblSection.SectionID = tblAdviser.SectionID) AND (tblDepartment.DepartmentID = tblAdviser.DepartmentID)" & _
" GROUP BY tblSection.SectionID, tblSection.SectionTitle, tblAdviser.SchoolYear, tblDepartment.DepartmentTitle, tblYearLevel.YearLevelTitle, tblAdviser.TeacherID" & _
" HAVING (((tblTeacher.TeacherID)='" & curTeacher.TeacherID & "') AND tblSection.SchoolYear='" & Me.txtSchoolYear.Text & "')" & _
" ORDER BY tblAdviser.SchoolYear DESC;"
If ConnectRS(con, vRS, sSQL) = False Then
'fatal
'temp
MsgBox "Unable to connect Teacher's Advisory Recordset.", vbCritical
'GoTo ReleaseAndExit
End If
If AnyRecordExisted(vRS) = True Then
While vRS.EOF = False
txtsection.AddItem vRS!SectionTitle
vRS.MoveNext
Wend
End If
'Exit Function
'ReleaseAndExit:
' Set vRS = Nothing
End Function
Take a look at this screenshot:
The HAVING clause references these 2 fields:
tblTeacher.TeacherID
tblSection.SchoolYear
The SELECT field list includes:
tblAdviser.TeacherID
tblAdviser.SchoolYear
Change the query so that all references to TeacherID come from the same table. Do the same for SchoolYear.
BTW, tblTeacher is not even included among the query's data sources.
If possible, start an Access session and use the query designer to build this query. It will help you avoid this type of error. Once you have a query which works in Access, then adapt your code to produce the same working SQL statement.
Group by has to be used with a aggregate function so that combined result for a group can be retrieved, you have not used any aggregate function.
Refer - http://www.w3schools.com/sql/sql_groupby.asp
Remove group by from your query and add the having clause in the where clause.
Explain what type of data you are expecting so that we can help you in the query.