Querying data from database with vb6 and ms access with adodb - sql

I want to select and view my data in the database, but it’s proving to be a challenge. Any advice on where I could be missing it? If I run this code even when the select criteria is met, it always returns search failed. Any help?
If txtSun.Text = "SUN" Then
Set rst = New ADODB.Recordset
Dim sSql As String
sSql = "SELECT * FROM SundryProduct WHERE ProdCont='" & txt_con_code.Text & "'"
rst.Open sSql, Cnn, adOpenForwardOnly, , adCmdText
'rst.Open "SELECT * FROM SundryProduct WHERE ProdCont='" & txt_con_code.Text & "' ", Cnn, adOpenForwardOnly, , adCmdText
If rst.EOF Then
MsgBox ("SEARCH FAILED")
Else
MsgBox ("QUANTITY ORDERED " & rst!QuantityOrdered & vbCrLf & " My Load Number is " & rst!LoadNumber)
End If
End If
I am trying to find out if there is a record with a matching ProdCont value in the database, but since I was still trying to make this code work in the first place I have only put messageboxes in the code. I have even tried putting in an actual value that I know exists in the database but it still returns the search failed messagebox even though I know the value exists in the database.

If rst.EOF = True Then '----> here
MsgBox ("SEARCH FAILED")
Else
MsgBox ("QUANTITY ORDERED " & rst!QuantityOrdered & vbCrLf & " My Load Number is " & rst!LoadNumber)
End If

What happens is you try to just run a simple query i.e. select * from SundryProduct?
I would start with that and build on it to eliminate the possibilty of coding/syntax causing the error message

Related

OpenRecordset not returning usable recordset / .edit not working?

Working on a database on Access, trying to run a query to find a record with the latest date and a 'where' condition.
Error returned is "Run Timer Error '3027' Cannot update. Database or object is read-only"
Following conditions:
Button is clicked on a form that contains a text field for 'fCheckInFor'.
Database 'ToolTests' fields
"CheckOut" is dates in format of "3/15/2019 5:35:31 PM"
"CheckIn" is dates in format of "3/15/2019 5:35:31 PM"
"CheckInFor" is a text field
"ToolNumber" is a text field
Public CheckInTool as String
Private Sub CheckIn_Click()
CheckInTool = "000"
If Me.fCheckInFor = "" Then
MsgBox "Enter Returning User."
Else
Dim dbsUE As DAO.Database
Dim rstUE As DAO.Recordset
Set dbsUE = CurrentDb
Set rstUE = dbsUE.OpenRecordset("SELECT Max([CheckOut]) FROM [ToolTests] WHERE [ToolNumber]= '" & CheckInTool & "'")
With rstUE
.Edit 'error occurs here
!CheckIn = Now()
!CheckInFor = Me.fCheckInFor
.Update
End With
MsgBox "Checked In"
DoCmd.Close acForm, "CheckIn"
End If
End Sub
So the error throws at the .Edit line, I'm unsure where to go from here. would also be fine with tossing the whole thing and going at it from a different direction.
If I get you right, you want to update a record that has a specific ToolNumber. So, if you want to use a subquery, you will either need to use that criterion in both the main query and the subquery, or link the subquery with the main query using that field:
Set rstUE = dbsUE.OpenRecordset( _ &
"SELECT CheckIn, CheckinFor FROM ToolTests WHERE" & _
" CheckOut IN (SELECT Max(CheckOut) FROM ToolTests AS tmp WHERE ToolNumber = ToolTests.ToolNumber)" & _
" And ToolNumber = '" & CheckInTool & "'")
Alternatively, you could simply sort the records in the correct order and update the first one:
Set rstUE = dbsUE.OpenRecordset( _ &
"SELECT CheckIn, CheckinFor FROM ToolTests WHERE" & _
" ToolNumber = '" & CheckInTool & "'" & _
" ORDER BY CheckOut DESC")

Update Sharepoint from Excel via ADO connection - Internal name issue

I need to update a SharePoint table which has a field name with Spaces. The field name is called Tracking log
Unfortunately there are lot of reports already created that don't let me recreate this column with a different name, so I need to find a workaround to address this special name.
Lot of blogs point me to revise the internal name and check the name given when it was created, so I checked the List Setting menu for the whole URL path and see the following:
https://sales.acs.com/SMS/_layouts/15/FldEdit.aspx?List=%7B686F9AF9%2DFB64%2D4AD9%2DA268%2D19A057C432DA%7D&Field=Tracking%5Fx0020%5Flog
Below is the script I've put together which runs perfectly fine for any other field without spaces in the name, but not specifically for this one.
Dim sSQL As String
' Build the connection string
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;RetrieveIds=Yes;" & "DATABASE=" & sSHAREPOINT_SITE & ";" & "LIST=" & sDEMAND_ROLE_GUID & ";Authentication=Default;"
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection.
With cn
.ConnectionString = sConn
.Open
End With
ID = "12345"
fieldName = "Tracking_x0020_log" 'Display view is "Tracking log", I've tried also with Tracking%5Fx0020%5Flog without luck
FieldValue = "Test"
'sSQL = "SELECT * FROM EMEA_SALES WHERE (APA_number='" & Format(ID, "#") & "');"
sSQL = "UPDATE EMEA_SALES SET " & fieldName & " = '" & FieldValue & "' WHERE (APA_number='" & Format(ID, "#") & "');"
rs.Open sSQL, cn, adOpenDynamic, adLockOptimistic
cn.Close
Set cn = Nothing
End Sub
The error I've got is:
No value given for one or more required parameters.
When I change the fieldname for any other without spaces is run smoothly.
Any clue will be appreciated. Thanks folks!

VBA Wait for DoCmd.RunSQL OR Better Query - Ms Access

I have a query which uses an array of tables (stored as a string array) to loop through my tables and perform a Delete/Update set of queries. The queries are identical other than the table names, hence using a loop to iterate through using the table name as a variable.
The problem is, my Delete query locks the table and the Update query runs too quickly afterward; I get a "db is locked" error.
I need either of two things:
A way to tell VBA to "wait for previous command" OR
A way to concatenate these queries into one (or two) queries: one to delete the database rows and another to import the new ones. With this I could just run the queries from a standard access query (which should allocate proper time, finish queries etc)
The only catch to this is that there are parent-child relations, so the parent table has to be updated before its children (currently accomplished through array ordering).
Here's the current code which (sometimes) produces the "DB locked/in use" message:
For i = 0 To UBound(tables)
'Delete all data first
sql = "DELETE * FROM " & tables(i)
DoCmd.RunSQL sql
'Update all data second
sql = "INSERT INTO " & tables(i) & " IN """ & toDB & """ SELECT " & tables(i) & " .* FROM " & tables(i) & " IN """ & fromDB & """;"
DoCmd.RunSQL sql
Next
Should clarify: the queries take one backend's (fromDB) rows from identical tables and pushes it to another backend's (toDB) rows
EDIT: In response to the questions regarding INSERT INTO, my problem with that is if I add fields to the toDB, it will delete them if I overwrite. The reason I have to do this backdoor approach is because the database is still in development, but is also being used with select tables. Updates and feature improvements are done daily. I cannot use a simple split-backend either, because the other computer accessing the database is not always on the network (we have to manually sync it when it returns to the network), so I work on one backend and it works on another, identical(ish, minus my schema update) backend.
You can use ADO instead of DoCmd.RunSQL to execute your SQL synchronously.
Dim cmd As ADODB.Command
Dim cnn As New ADODB.Connection
Set cnn = CurrentProject.Connection
For i = 0 To UBound(tables)
Set cmd = New ADODB.Command
With cmd
.CommandType = adCmdText
.ActiveConnection = cnn
.CommandText = "DELETE * FROM " & tables(i)
.Execute
End With
Set cmd = New ADODB.Command
With cmd
.CommandType = adCmdText
.ActiveConnection = cnn
.CommandText = "INSERT INTO " & tables(i) & " IN """ & toDB & """ SELECT " & tables(i) & " .* FROM " & tables(i) & " IN """ & fromDB & """;"
.Execute
End With
Next
You could also add cnn.BeginTrans and cnn.CommitTrans to make the two statements Atomic.
Try something like this (Note I've commented your DoCmd.RunSQL. I changed it with db.Execute:
Sub DeleteInsertData(tables() As String, toDB As String, fromDB As String)
Dim db As DAO.Database
Dim i As Integer
Dim SQL As String
Set db = CurrentDb()
For i = 0 To UBound(tables)
'Delete all data first
SQL = "DELETE * FROM " & tables(i)
db.Execute SQL, dbFailOnError
'DoCmd.RunSQL SQL
'Update all data second
SQL = "INSERT INTO " & tables(i) & " IN """ & toDB & """ SELECT " & tables(i) & " .* FROM " & tables(i) & " IN """ & fromDB & """;"
db.Execute SQL, dbFailOnError
'DoCmd.RunSQL SQL
Next
Set db = Nothing
End Sub
I'm no expert, but I don't think you need the DELETE part. SELECT INTO is the syntax for making a table. If the table already exists, it's overwritten.
If I need to wait for something, I tend to use DoEvents to allow windows to process any other actions that have been put on hold.
From the help: "Yields execution so that the operating system can process other events."
Found this:
.BeginTrans then
.CommitTrans dbForceOSFlush
as a way to force updates to be written before continuing

query syntax error...

I have the following coding for a button. My problem is that the Query "SQLStory" is comming up with an error that it is missing a semi colon.
The combobox contains the item name and is ordered by the product ID and the SQLStory is supposed to move all items from the TblTotalSale to the table TblSaleStore. Any Ideas where the error is?
Private Sub StockOK_Click()
Dim SQLDelete1 As String
Dim SQLDelete2 As String
Dim SQLUpdate As String
Dim SQLStory As String
SQLDelete1 = "DELETE * FROM TblStock WHERE TblStock.ProductID = " & CboStockItem.Value
SQLDelete2 = "DELETE * FROM TblTotalSale WHERE TblTotalSale.ProductID = " & CboStockItem.Value
SQLUpdate = "INSERT INTO TblStock (ProductID, StockLevel) VALUES ( " & Me.CboStockItem.Value & "," & Me.TxtStockValue & " )"
SQLStory = "INSERT INTO TblSaleStore (ProductID) VALUES (TblTotalSale.ProductID) FROM TblTotalSale WHERE TblTotalSale.ProductID = " & Me.CboStockItem.Value
If IsNull(Me.TxtStockValue) Then MsgBox "Please Select An Item To Update Stock And Ensure A Value Has Been Entered" Else:
DoCmd.RunSQL SQLDelete1
DoCmd.SetWarnings False
DoCmd.RunSQL SQLStory
DoCmd.RunSQL SQLDelete2
DoCmd.RunSQL SQLUpdate
DoCmd.SetWarnings True
End Sub
Another problem I am having with this code is that the block of doCmd was happening whether the txt box TxtStockValue was null or not, and I only want them to happen if the box is not null... Any Ideas on that part either?
Thanks
Sam
Values are for just that, values such as 'abc' or 123, you need SELECT:
SQLStory = "INSERT INTO TblSaleStore (ProductID) " _
& "SELECT (TblTotalSale.ProductID) FROM " _
& "TblTotalSale WHERE TblTotalSale.ProductID = " _
& Me.CboStockItem.Value
But the above is odd, because you already have the ID in the combo, so, as I said in your previous post on the topic:
SQLStory = "INSERT INTO TblSaleStore (ProductID) " _
& "VALUES ( " & Me.CboStockItem.Value & " )"
Also, it was suggested to you that you should use debug.print when using SQL, this would allow you to view the SQL and paste it into the query design window to see if it worked. The debug.print line can be commented out when everything is working. When you are unfamiliar with SQL, there is a lot to be said for using the query design window to build your queries. You can then cut the SQL from SQL View and add quotes etc.
EDIT re Question Part 2
Dim db As Database
Set db = CurrentDB
If IsNull(Me.TxtStockValue) Then
MsgBox "Please Select An Item To Update Stock " _
& "And Ensure A Value Has Been Entered"
Else
db.Execute SQLDelete1, dbFailOnError
''DoCmd.SetWarnings False
db.Execute SQLStory, dbFailOnError
db.Execute SQLDelete2, dbFailOnError
db.Execute SQLUpdate, dbFailOnError
''DoCmd.SetWarnings True
End If

Syntax Error in From clause Deleting record with ADO

I'm using ADO to delete a record in my MS Access 2007 database and am at a total loss as to why I'm getting this syntax error for my SQL code. It claims there is an error in the FROM clause but I do not see it. I have taken the FROM clause directly from a working SQL statement in another module using the same table. I've entered the code into the SQL View of a new query and it runs just fine. Here is the code:
Private Sub cmdDeleteMessage_Click()
If MsgBox("Once you delete a message, it cannot be undone." & _
"Are you sure you want to delete this message?", vbYesNo) = vbYes Then
Dim sql As String
Dim rsDel As New ADODB.Recordset
rsDel.CursorType = adOpenDynamic
rsDel.LockType = adLockOptimistic
sql = "DELETE * FROM [Staff Notes] WHERE [MsgID] = " & Me.txtMsgID.Value & ";"
rsDel.Open sql, CurrentProject.AccessConnection, , , adCmdTable
With rsDelete
.Update
.Close
End With
End If
End Sub
And Ideas? Thanks in advance!
You're trying to run an action query but using a recordset (which expects a select query).
Try this:
sql = "DELETE * FROM [Staff Notes] WHERE [MsgID] = " & Me.txtMsgID.Value & ";"
CurrentProject.AccessConnection.Execute sql, , adExecuteNoRecords
Also, if [MsgID] is a string, you need to enclose your value in quotes:
sql = "DELETE * FROM [Staff Notes] WHERE [MsgID] = " & Chr$(34) & Me.txtMsgID.Value & Chr$(34) & ";"