How to retrieve value from database and display in textbox - mysql

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.

Related

Nested loop to update recordset not working Access

I am planning to search and update records which matches my criteria in my table through a form.
I want my code to search for OrderNo and OrderNoItem ( For each orderno I have multiple OrderNoItems like 10,20,30... in my table) when there is a match I want to update the customer name(Text18.Value) from my Form.
I have the following code. For some reason it is just updating only the first record. For example when I input Text25.Value = 12345, Text27.Value = 20 and Text49.Value = 40, it is updating the customer name only for the rows with 12345 and 20. Can any one help??
Set logDB1 = CurrentDb()
Set logRS1 = logDB1.OpenRecordset("Log")
For i = Text27.Value To Text49.Value Step 10
Do Until logRS1.EOF
If (logRS1![OrderNo] = Text25.Value And logRS1![OrderNoItem] = Text27.Value) Then
logRS1.Edit
logRS1![DTN-#] = Text18.Value
logRS1.Update
End If
logRS1.MoveNext
Loop
Next
Because code is set to do that. That's exactly what the If condition requires. What you should do is open the recordset filtered by OrderNo and the OrderNoItem range then just loop those records.
Set logDB1 = CurrentDb()
Set logRS1 = logDB1.OpenRecordset("SELECT [DTN-#] FROM Log WHERE OrderNo='" & _
Me.Text25 & "' AND Val(OrderNoItem) BETWEEN " & Me.Text27 & " AND " & Me.Text49)
Do Until logRS1.EOF
logRS1.Edit
logRS1![DTN-#] = Me.Text18
logRS1.Update
logRS1.MoveNext
Loop
Or instead of opening and looping recordset, Execute an UPDATE action SQL:
CurrentDb.Execute "UPDATE Log SET [DTN-#]='" & Me.Text18 & _
"' WHERE OrderNo = '" & Me.Text25 & "' AND Val(OrderNoItem) BETWEEN " & Me.Text27 & " AND " & Me.Text49
If OrderNo is a number field, remove the apostrophe delimiters.
Strongly advise not to use punctuation/special characters (underscore is only exception) in naming convention. Better would be DTN_Num.

MS Access vba to change values in a column

I need to change values in a column titled "CURRENT QUARTER" from .NULL. to "2017 Q2" the number of values is very large so I am trying to more than 10,000 so need to do it via a macro. Any one knows how to do this? I only have experience on VBA in excel
You can create a saved update query and run it. Or:
Dim sqltext as string
sqltext = "Update tablename SET [CURRENT QUARTER] = " & chr(34) & 2017 Q2 &chr(34) & "WHERE [CURRENT QUARTER] Is Null;"
Docmd.RunSql sqltext
Replace tablename with the name of your table.

Microsoft Access insert query

Access table Allowances_3_15_18 has 5 columns. I want to insert a calculated field from a form EmployeeSalary) into one of the columns Amount in the table.
Each value will link with the relevant primary ID's from the form and the table which are the same JobID. How do I do this in VBA?
I currently have done it in the afterUpdate event in the property sheet.
Private Sub ProjectedDollarAmount_AfterUpdate()
Dim strSQL As String
Dim ProjectedDollarAmount As Currency
strSQL = "INSERT INTO [Allowances_3_15_18] ([Amount]) VALUES (" & _
PrepareSQLNumber(Me.ProjectedDollarAmount) & ") WHERE JobID = " & _
PrepareSQLNumber(Me.JobID) & ";"
Call ExecuteMyCommand(strSQL)
End Sub
You need to get away from SQL concatenation and start using parameters.
Create a query with two parameters, the amount to be inserted and the JobId. The query's SQL should be something like this:
PARAMETERS [prmAmount] Currency, [prmJobId] Long;
UPDATE [Allowances_3_15_18] SET [Amount] = [prmAmount]
WHERE JobID = [prmJobId];
Then in code, simply pass the parameter values and execute the above query:
Sub Add()
With CurrentDb().QueryDefs("qryName")
.Parameters("[prmAmount]").Value = PrepareSQLNumber(Me.ProjectedDollarAmount)
.Parameters("[prmJobId]").Value = PrepareSQLNumber(Me.JobID)
.Execute dbFailOnError
End With
End Sub
You need to change the qryName to the actual name of the query.
You can read more about parameter queries here.

How to count number of fields in a table?

I am trying to count number of fields in a table in Access 2010. Do I need a vb script?
You can retrieve the number of fields in a table from the .Count property of the TableDef Fields collection. Here is an Immediate window example (Ctrl+g will take you there) ...
? CurrentDb.TableDefs("tblFoo").Fields.Count
13
If you actually meant the number of rows instead of fields, you can use the TableDef RecordCount property or DCount.
? CurrentDb.TableDefs("tblFoo").RecordCount
11
? DCount("*", "tblFoo")
11
Using a query:
'To get the record count
SELECT Count(*) FROM MyTable
In DAO it would look like:
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("SELECT * FROM MyTable")
rst.MoveLast
'To get the record count
MsgBox ("You have " & rst.RecordCount & " records in this table")
'To get the field count
MsgBox ("You have " & rst.Fields.Count & " fields in this table")
Note, it is important to perform the MoveLast before getting the RecordCount.
In ADO it would look like:
Set conn = Server.CreateObject("ADODB.Connection")
conn.Provider = "Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("MyDatabaseName.mdb"))
Set rst = Server.CreateObject("ADODB.recordset")
rst.Open "SELECT * FROM MyTable", conn
'To get the record count
If rst.Supports(adApproxPosition) = True Then _
MsgBox ("You have " & rst.RecordCount & " records in this table")
'To get the field count
MsgBox ("You have " & rst.Fields.Count & " fields in this table")
Quick and easy method: Export the table to Excel and highlight row 1 to get number of columns.

ODBC select statement to get a boolean

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