CurrentDb.Execute "UPDATE Customer set [FirstName] = " & Me.FirstName & _
" ,[LastName] = " & Me.LastName & _
" ,[PhoneNumber] = '" & Me.PhoneNumber & _
"' ,[Address] = '" & Me.Address & _
"' ,[City] = " & Me.City & _
" ,[State] = " & Me.State & _
" ,[ZipCode] = " & Me.ZipCode & " WHERE ([E-mail] = '" & Me.email & "')"
what is wrong with this update query. Please help.
Once again, consider SQL parameterization, an industry best practice when working with SQL, which is supported in MS Access using PARAMETERS clause and QueryDefs. You avoid messy concatenation, quote enclosures (which you are missing quite a bit for your text fields), and possibly SQL injection as such fields are open to users.
SQL (save as a stored Access query)
PARAMETERS [FirstNameParam] Text(255), [LastNameParam] Text(255),
[PhoneNumberParam] Text(255), [AddressParam] Text(255),
[CityParam] Text(255), [StateParam] Text(255),
[ZipCodeParam] Text(255), [EmailParam] Text(255);
UPDATE Customer
SET [FirstName] = [FirstNameParam],
[LastName] = [LastNameParam],
[PhoneNumber] = [PhoneNumberParam],
[Address] = [AddressParam],
[City] = [CityParam],
[State] = [StateParam],
[ZipCode] = [ZipCodeParam]
WHERE ([E-mail] = [EmailParam]);
VBA
Dim qdef As QueryDef
Set qdef = CurrentDb.QueryDefs("mySavedParameterQuery")
' BIND VALUES TO PARAMETER PLACEHOLDERS
qdef![FirstNameParam] = Me.FirstName
qdef![LastNameParam] = Me.LastName
qdef![PhoneNumberParam] = Me.PhoneNumber
qdef![AddressParam] = Me.Address
qdef![CityParam] = Me.City
qdef![StateParam] = Me.State
qdef![ZipCodeParam] = Me.ZipCode
qdef![EmailParam] = Me.Email
' EXECUTE ACTION QUERY
qdef.Execute dbFailOnError
Set qdef = Nothing
Just a guess from looking at your SQL and the error - I suspect your 4 field names with two words should likely have spaces between the two words: [FirstName] becomes [First Name], [Last Name] becomes [Last Name] and so on
So SQL string should actually be
"UPDATE Customer set [First Name] = " & Me.FirstName & _
" ,[Last Name] = " & Me.LastName & _
" ,[Phone Number] = '" & Me.PhoneNumber & _
"' ,[Address] = '" & Me.Address & _
"' ,[City] = " & Me.City & _
" ,[State] = " & Me.State & _
" ,[Zip Code] = " & Me.ZipCode & " WHERE ([E-mail] = '" & Me.email & "')"
As #Jiggles32 says - the only way to know for sure is to show us your field names from the Customer table
Related
I'm trying to filter a OLEDB command by having multiple 'OR' statements work on a single database field but the last in the chain gets ignored and doesn't return anything.
I have a work around for now with a #null request that returns "DBNull.value" but if I remove "[doctype] = #null" from below it ignores "[doctype] = doctype3"
& "WHERE [doctype] = #doctype OR [doctype] = #doctype2 OR [doctype] = #doctype3 OR [doctype] = #null " _
I can increase or decrease the 'OR Statements' as I like but it is always the last 'OR Statement' that is ignored.
I've tried putting the 'OR statements' in brackets but then it returns nothing, or I'm doing it wrong.
I'm looking for simply why the last 'or statement' is ignored in the oledbcommand string but if you can improve any code I've wrote please do, but explain to me why/how.
Where they are used (Every other value has DBNull.value for testing purposes)
f_doctype = "MS"
f_doctype2 = "TMS"
f_doctype3 = "CS"
With cmdaRefresh.Parameters
.AddWithValue("doctype", CType(f_doctype, String))
.AddWithValue("doctype2", CType(f_doctype2, String))
.AddWithValue("doctype3", CType(f_doctype3, String))
.AddWithValue("null", DBNull.Value)
.AddWithValue("docnum", DBNull.Value)
.AddWithValue("docrev", DBNull.Value)
.AddWithValue("matname", DBNull.Value)
.AddWithValue("status", DBNull.Value)
.AddWithValue("actionreq", DBNull.Value)
.AddWithValue("createdby", DBNull.Value)
.AddWithValue("createddate", DBNull.Value)
.AddWithValue("finalby", DBNull.Value)
.AddWithValue("finaldate", DBNull.Value)
End With
Dim cmdRefresh As New OleDbDataAdapter(cmdaRefresh)
'open connection
myconnection.Open()
'read and fill dataset for gridview
cmdRefresh.Fill(dsRefresh, tbl_string.tablename)
'close connection
myconnection.Close()
'fill datagrid with values from database and alter column headers to match criteria
With dg_speclog
.DataSource = dsRefresh.Tables(0)
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "Category"
...
End With
Full 'oledbcommand' creation
Dim cmdaRefresh As OleDbCommand = New OleDbCommand(" SELECT [doctype], [docnum], [docrev], [matname], [status], [actionreq], [createdby], [createddate], [finalby], [finaldate] " _
& "FROM " & tbl_string.tablename & " " _
& "WHERE [doctype] = #doctype OR [doctype] = #doctype2 OR [doctype] = #doctype3 OR [doctype] = #null " _
& "AND [docnum] = #docnum " _
& "AND [docrev] = #docrev " _
& "AND [matname] = #matname " _
& "AND [status] = #status " _
& "AND [actionreq] = #actionreq " _
& "AND [createdby] = #createdby " _
& "AND [createddate] = #createddate " _
& "AND [finalby] = #finalby " _
& "AND [finaldate] = #finaldate " _
& "ORDER BY [docnum] ASC, [docrev] ASC " _
, myconnection)
You need to use IS NULL to check for null values (in most, perhaps all, databases, null does not equal null, so you need to use the IS operator instead). This also means you don't need all those parameters.
Depending on how you intend to combine the [doctype] IS NULL check with the other null checks, you may also need to wrap the ORs in parentheses, since AND may have higher precedence than OR.
Dim cmdaRefresh As OleDbCommand = New OleDbCommand(
" SELECT [doctype], [docnum], [docrev], [matname], [status], [actionreq], [createdby], [createddate], [finalby], [finaldate] " _
& "FROM " & tbl_string.tablename & " " _
& "WHERE ([doctype] = #doctype OR [doctype] = #doctype2 OR [doctype] = #doctype3 OR [doctype] IS NULL) " _
& "AND [docnum] IS NULL " _
& "AND [docrev] IS NULL " _
& "AND [matname] IS NULL " _
& "AND [status] IS NULL " _
& "AND [actionreq] IS NULL " _
& "AND [createdby] IS NULL " _
& "AND [createddate] IS NULL " _
& "AND [finalby] IS NULL " _
& "AND [finaldate] IS NULL " _
& "ORDER BY [docnum] ASC, [docrev] ASC " _
, myconnection)
If the[doctype] IS NULL check belongs with the other NULL checks then you don't need the parens.
Found the reason why it wasn't working. Somewhere during my search I read that DBNull.value would return anything from the database when used with a .addwithvalue statement (which might of confused the whole thing). Which is not correct, it returns anything that has a value of nothing as in no white space or value. Which is why [doctype] IS NULL gave the same issue as above, it does the same thing, I think.
What I was looking for was a way to search through my [doctype]'s and return any value from the other database fields without having to specify anything 'for testing'
The statement I was looking for was [docnum] LIKE '%' this is called a Wildcard. A wildcard character can be used to substitute for any other character(s) in a string, so that mean anything is returned. However if the database field is of value Null then a IS NULL statement is still require, hence my [finalyby] & [finaldate] alterations below.
What I've came up with now is:
'CHANGED (dataadapter > command)
Dim cmdaRefresh As OleDbCommand = New OleDbCommand(" SELECT [doctype], [docnum], [docrev], [matname], [status], [actionreq], [createdby], [createddate], [finalby], [finaldate] " _
& "FROM " & tbl_string.tablename & " " _
& "WHERE [doctype] IN (#doctype, #doctype2 ,#doctype3) " _
& "AND [docnum] LIKE '%' " _
& "AND [docrev] LIKE '%' " _
& "AND [matname] LIKE '%' " _
& "AND [status] LIKE '%' " _
& "AND [actionreq] LIKE '%' " _
& "AND [createdby] LIKE '%' " _
& "AND [createddate] LIKE '%' " _
& "AND ([finalby] LIKE '%' OR [finalby] IS NULL) " _
& "AND ([finaldate] LIKE '%' OR [finaldate] IS NULL) " _
& "ORDER BY [docnum] ASC, [docrev] ASC " _
, myconnection)
Thank you to who helped.
So i have these two query in my access VBA code. The When I replace like with = i end up retrieving no records. the like works perfectly with out a hitch but I can't use it because sometimes it'll pull up the wrong data. What am I doing wrong with the = operator?
Set rsStepCalendar = db.OpenRecordset("Select * from tblStepCalendar " & _
"Where (groupNr = '*" & txtGroupNum.Value & "*' ) " & _
"AND (Cancel = False)", dbOpenDynaset)
Set rs = db.OpenRecordset("Select * from tblContacts " & _
"Where (groupNum = '*" & txtGroupNum.Value & "*' ) " & _
"AND (canceledContact = False)", dbOpenDynaset)
groupNum = '*" & txtGroupNum.Value & "*'
Is looking for the value surrounded by asterisk characters which only have symbolic meaning as "anything" when combined with LIKE.
For = use groupNum = '" & txtGroupNum.Value & "'
You should also escape any user input/use parametrized queries.
I got syntax error in update statement.Run-time error: 3144
I use the following code
CurrentDb.Execute "UPDATE product " & _
" SET [product name] = '" & Me.txtName & "'" & _
", [cost of product] = " & Me.txtCost & "" & _
", [weight] = " & Me.txtWeight & "" & _
", [group] = '" & Me.CmbGroup & "'" & _
", [group ID] = '" & Me.txtGroupID & "'" & _
", [Ordered] = " & Me.txtOrdered & "" & _
" WHERE [roduct name] = " & Me.txtName.Tag & ""
What can be the problem?
If it makes sense, then Me.txtCost , Me.txtWeight and me.txtOrdered are number
Thanks for your help!
Two problems that I see:
Typo in WHERE [roduct name] (should be WHERE [product name])
Missing quotes around Me.txtName.Tag at the end of the statement
Try this instead:
CurrentDb.Execute "UPDATE product " & _
" SET [product name] = '" & Me.txtName & "'" & _
", [cost of product] = " & Me.txtCost & "" & _
", [weight] = " & Me.txtWeight & "" & _
", [group] = '" & Me.CmbGroup & "'" & _
", [group ID] = '" & Me.txtGroupID & "'" & _
", [Ordered] = " & Me.txtOrdered & "" & _
" WHERE [product name] = '" & Me.txtName.Tag & "'"
To future readers of this post, reconsider interpolating or concatenating VBA values into a dynamic SQL query. Consider parameterized queries with MS Access' QueryDefs. This will avoid mistyping, misquoting, and unreadable, and unmaintainable code.
SQL (save as an MS Access stored query only once)
PARAMETERS [txtName_PARAM] TEXT, [txtCost_PARAM] DOUBLE,
[txtWeight_PARAM] DOUBLE, [CmbGroup_PARAM] TEXT,
[txtGroupID_PARAM] TEXT, [txtOrdered_PARAM] LONG,
[txtName_Tag_PARAM] TEXT;
UPDATE product
SET [product name] = [txtName_PARAM],
[cost of product] = [txtCost_PARAM],
[weight] = [txtWeight_PARAM],
[group] = [CmbGroup_PARAM],
[group ID] = [txtGroupID_PARAM],
[Ordered] = [txtOrdered_PARAM],
WHERE [product name] = [txtName_Tag_PARAM];
VBA (dynamically bind values to parameter placeholders)
Dim qdef as QueryDef
Set qdef = CurrentDb.QueryDefs("mySavedQuery")
qdef![txtName_PARAM] = Me.txtName
qdef![txtCost_PARAM] = Me.txtCost
qdef![txtWeight_PARAM] = Me.txtWeight
qdef![CmbGroup_PARAM] = Me.CmbGroup
qdef![txtGroupID_PARAM] = Me.txtGroupID
qdef![txtOrdered_PARAM] = Me.txtOrdered
qdef![txtName_Tag_PARAM] = Me.txtName.Tag
qdef.Execute dbFailOnError
Set qdef = Nothing
I have tried and tried to get this peice of code working but with no luck.
The code is supposed to pick products that have the same sections of product code as cmbsource.
Private Sub cmbSource_AfterUpdate()
Dim Worktop As String
If ProductType = 1 Then
Worktop = "SELECT [products/stock].[Product Code], [products/stock].Description, [products/stock].[Stock Level] FROM [products/stock] " & _
"WHERE Category = 'DPALRC' " & _
"AND Mid('[Product Code]',1,5) = Mid('" & Me.cmbSource.Value & "',1,5) " & _
"AND Mid('[Product Code]',9,6) = Mid('" & Me.cmbSource.Value & "',9,6) " & _
"ORDER BY [Product Code];"
Me.cmbResult.rowSource = Worktop
Me.cmbResult = vbNullString
End If
Any Ideas?
Thanks in advance,
Bob P
Just a wild guess here.
Worktop = "SELECT ps.[Product Code], ps.Description, ps.[Stock Level]" & vbCrLf & _
"FROM [products/stock] AS ps" & vbCrLf & _
"WHERE ps.Category = 'DPALRC'" & vbCrLf & _
"AND Mid([Product Code],1,5) = '" & Mid(Me.cmbSource,1,5) & "'" & vbCrLf & _
"AND Mid([Product Code],9,6) = '" & Mid(Me.cmbSource,9,6) & "'" & vbCrLf & _
"ORDER BY ps.[Product Code];"
Debug.Print Worktop
Go to the Immediate window (Ctrl+g) and copy the statement from there. Then create a new Access query, switch to SQL View, paste in the statement text, and run it.
If the code I suggested does not return the results you want, show us the actual SQL statement text and explain what is wrong with it.
Worktop = "SELECT [products/stock].[Product Code], [products/stock].Description, [products/stock].[Stock Level] FROM [products/stock] " & _
"WHERE Category = 'DPALRC' " & _
"AND Mid([Product Code],1,5) = Mid('" & Me.cmbSource.Value & "',1,5) " & _
"AND Mid([Product Code],9,6) = Mid('" & Me.cmbSource.Value & "',9,6) " & _
"ORDER BY [Product Code];"
This is my updated version, turns out the only error in the coding was having the single quotes around [Product Code].
Dim conn As OleDbConnection
Dim cmd As OleDbCommand
Public Sub openDB()
conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\VFMS_DB.mdb;" & "Jet OLEDB:System Database=Security.mdw;User ID=Adster;Password=300624;")
conn.Open()
End Sub
Public Function UpdateUser() As Integer
Dim retCode As New Integer
Try
openDB()
cmd = conn.CreateCommand()
The update command below keeps giving me this error: "Conversion from string "' WHERE [Username] = '" to type 'Double' is not valid." and I don't know why. The aUserName field is a String field and I checked to make sure it's populated.
cmd.CommandText = "UPDATE Users SET [First Name] = '" & aName & "', [Last Name] = '" & aSurname & "', [Contact Number] = '" & aContactNum & "', [Password] = '" & aPassword & "', [User Rights] = '" & aUserRights + "' WHERE [Username] = '" + aUserName + "' "
cmd.ExecuteNonQuery()
conn.Close()
'rsAddRecs = rsConn.Execute("UPDATE Users ([First Name], [Last Name], [Contact Number], [User Name], [Password], [User Rights]) VALUES ('" & aName & "','" & aSurname & "','" & aContactNum & "','" & aUserName & "','" & aPassword & "','" & aUserRights & "')")
retCode = 0
'rsConn.Close()
Return retCode
Catch ex As Exception
MessageBox.Show(ex.ToString, ex.Message, MessageBoxButtons.OK)
retCode = 1
Return retCode
End Try
End Function
You have a typo. You're using + concat characters at the end of the sql string instead of & characters
Wrong
cmd.CommandText = "UPDATE Users SET [First Name] = '" & aName & _
"', [Last Name] = '" & aSurname & _
"', [Contact Number] = '" & aContactNum & _
"', [Password] = '" & aPassword & "', [User Rights] = '" & _
aUserRights + "' WHERE [Username] = '" + aUserName + "' "
' ^ ^ ^
Right
cmd.CommandText = "UPDATE Users SET [First Name] = '" & aName & _
"', [Last Name] = '" & aSurname & _
"', [Contact Number] = '" & aContactNum & _
"', [Password] = '" & aPassword & "', [User Rights] = '" & _
aUserRights & "' WHERE [Username] = '" & aUserName & "' "
' ^ ^ ^
You SQL code uses [Username]:
cmd.CommandText = "UPDATE Users SET ... [Username]...
Whereas you commented out code used [User Name]:
'rsAddRecs = rsConn.Execute("UPDATE Users ... [User Name]...
Could the wrong column name be the source of the problem?
Another thought: have you sanitized your parameter values e.g. could the value contain a single quote that is upsetting the dynamic SQL. In any case, I think you should consider using prepared statements (or even PROCEDURES) and using Parameter objects to call the SQL, thereby deferring the sanitizing of the parameter values to the OLE DB provider, which will of course know more about the subject than you or I :)