Unclosed Quotation mark after the character string 'test' - sql

I have been racking my brain with searching on the internet for the solution, but to no avail, I have been unsuccessful.
strSQL = "Update tTbl_LoginPermissions SET LoginName = '" & StrUserName & "', PWD = '" & StrPWD & "', fldPWDDate = '" & Now() & "'" & _
"WHERE intLoginPermUserID = " & MyMSIDColumn0
Once I get the error out, I would like to actually use this where clause:
'WHERE intLoginPermUserID IN (SELECT intCPIIUserID From vw_ADMIN_Frm_LoginBuilder)
Here is the entire code:
Dim con As ADODB.Connection
Dim cmd As ADODB.Command
Dim strSQL As String
Const cSQLConn = "DRIVER=SQL Server;SERVER=dbswd0027;UID=Mickey01;PWD=Mouse02;DATABASE=Regulatory;"
Dim StrUserName As String, StrPWD As String
'passing variables
StrUserName = FindUserName()
StrPWD = EncryptKey(Me.TxtConPWD)
'Declaring the SQL expression to be executed by the server
strSQL = "Update tTbl_LoginPermissions SET LoginName = '" & StrUserName & "', PWD = '" & StrPWD & "', fldPWDDate = '" & Now() & "#" & _
"WHERE intLoginPermUserID = " & MyMSIDColumn0
'WHERE intLoginPermUserID = ANY (SELECT intCPIIUserID From vw_ADMIN_Frm_LoginBuilder)
Debug.Print strSQL
'connect to SQL Server
Set con = New ADODB.Connection
With con
.ConnectionString = cSQLConn
.Open
End With
'write back
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = con
.CommandText = strSQL
.CommandType = adCmdText
.Execute
Debug.Print strSQL
End With
'close connections
con.Close
Set cmd = Nothing
Set con = Nothing
MsgBox "You password has been set", vbInformation + vbOKOnly, "New Password"
NEWEST CODE Producing Error:
'/Declaring the SQL expression to be executed by the server
strSQL = "Update dbo_tTbl_LoginPermissions " _
& "SET LoginName = '" & StrUserName & "' " _
& "SET PWD = '" & StrPWD & "' " _
& "SET fldPWDDate = '" & Now() & "' " _
& "WHERE intLoginPermUserID = 3;"
I have gone to this site to try to figure out my mistake, but I still cannot figure it out:

After much dilberation and help, it turns out the FindUserName that utilizes a Win32API function was not trimming the Username appropriately.
I changed it to the following:
Public Function FindUserName() As String
' This procedure uses the Win32API function GetUserName
' to return the name of the user currently logged on to
' this machine. The Declare statement for the API function
' is located in the Declarations section of this module.
Dim strBuffer As String
Dim lngSize As Long
strBuffer = Space$(255)
lngSize = Len(strBuffer)
If GetUserName(strBuffer, lngSize) = 1 Then
FindUserName = Left$(strBuffer, lngSize - 1)
Else
FindUserName = "User Name not available"
End If
End Function
Public Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Try this:
strSQL = "Update tTbl_LoginPermissions SET LoginName = '" & replace(StrUserName, "'", "''") & "', PWD = '" & replace(StrPWD, "'", "''") & "', fldPWDDate = '" & Now() & "'" & _
"WHERE intLoginPermUserID = " & MyMSIDColumn0

This was inevitably the code that corrected my (') mystery:
'/passing variables
StrUserName = FindUserName()
StrPWD = EncryptKey(Me.TxtConPWD)
StrUserId = Me.CboUser.Column(0)
'/Declaring the SQL expression to be executed by the server
strSQL = "Update tTbl_LoginPermissions SET " _
& "LoginName = '" & StrUserName & "' , " _
& "PWD = '" & StrPWD & "' ," _
& "fldPWDDate = '" & Now() & "' " _
& "WHERE intLoginPermUserID = '" & StrUserId & "'"

Related

Data Type Mismatch error while using the SQL Update query

I am using SQL update query in VBA and I am getting the datatype mismatch error. I know that error is basically because of the column spare part. The spare part column contains numeric and alphanumeric values.
Public Function UpdateDistinctColumnFRNumberBasis()
StrInvoiceNumber = "109839-01"
FRSparepartNumber = "FT7119907459"
MergedInvoiceFile = "/test.xlsx"
Dim objConn As Object
Dim objRecordSet As Object
Set objConn = CreateObject("ADODB.Connection")
Set objRecCmd = CreateObject("ADODB.Command")
Set objRecCmd_Update = CreateObject("ADODB.Command")
objConn.Open ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
MergedInvoiceFile & ";Extended Properties=""Excel 8.0;""")
strSQL = " Update [Tabelle1$] SET [Status] = 'Include' Where " & _
"([RECHNR] ='" & StrInvoiceNumber & "' AND [Sparepart] = " & FRSparepartNumber & ")"
objConn.Execute strSQL
objConn.Close
End Function
As commented, the partnumber is text, thus it must be quoted in the SQL:
FRSparepartNumber = "FT7119907459"
' snip
strSQL = "Update [Tabelle1$] SET [Status] = 'Include' Where " & _
"([RECHNR] = '" & StrInvoiceNumber & "' AND " & _
"[Sparepart] = '" & FRSparepartNumber & "')"

Is there a better way to write this Access SQL expression?

I have an Access database that I use to track personnel going on trips. When I add someone to a trip, it copies over some information items from the master personnel table into another table that ties that person to the trip and then displays readiness things that I need to track. I'm in the process of updating how the front end talks to the back end in preparation for migrating this over to a proper SQL server rather than just a backend file on a share drive, and was wondering if there was a better way to code this.
Here's the original code:
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("tblMsnPers")
rst.AddNew
rst![MsnID] = Me.ID
rst![EDIPI] = Me.PerSelect
rst![NameStr] = DLookup("[NameStr]", "tblPersonnel", "[EDIPI] = '" & Me.PerSelect & "'")
rst![PriAlt] = Me.cmbPriAlt
rst![Errors] = DLookup("[ScrubErrors]", "tblPersonnel", "[EDIPI] = '" & Me.PerSelect & "'")
rst![PT] = DLookup("[ScrubFitDate]", "tblPersonnel", "[EDIPI] = '" & Me.PerSelect & "'")
rst![vRED] = DLookup("[ScrubvRED]", "tblPersonnel", "[EDIPI] = '" & Me.PerSelect & "'")
rst![ISOPREP] = DLookup("[ISOPREP]", "tblPersonnel", "[EDIPI] = '" & Me.PerSelect & "'")
rst![2760] = DLookup("[Scrub2760]", "tblPersonnel", "[EDIPI] = '" & Me.PerSelect & "'")
rst![Checklist] = DLookup("[ScrubStatus]", "tblPersonnel", "[EDIPI] = '" & Me.PerSelect & "'")
rst![IMR] = DLookup("[ScrubShots]", "tblPersonnel", "[EDIPI] = '" & Me.PerSelect & "'")
rst![Review] = DLookup("[ReviewDate]", "tblPersonnel", "[EDIPI] = '" & Me.PerSelect & "'")
rst.Update
rst.Close
Set rst = Nothing
And here is what my updated code is:
DoCmd.SetWarnings False
SqlStr = "INSERT INTO tblMsnPers " _
& "(MsnID, EDIPI, PriAlt) VALUES " _
& "('" & Me.ID & "', '" & Me.PerSelect & "', '" & Me.cmbPriAlt & "');"
DoCmd.RunSQL SqlStr
SqlStr2 = "UPDATE tblMsnPers INNER JOIN tblPersonnel ON tblMsnPers.EDIPI = tblPersonnel.EDIPI " _
& "SET tblMsnPers.NameStr = [tblPersonnel].[NameStr], " _
& "tblMsnPers.Errors = [tblPersonnel].[ScrubErrors], " _
& "tblMsnPers.PT = [tblPersonnel].[ScrubFitDate], " _
& "tblMsnPers.vRED = [tblPersonnel].[ScrubvRED], " _
& "tblMsnPers.ISOPREP = [tblPersonnel].[ISOPREP], " _
& "tblMsnPers.[2760] = [tblPersonnel].[Scrub2760], " _
& "tblMsnPers.Checklist = [tblPersonnel].[ScrubStatus], " _
& "tblMsnPers.IMR = [tblPersonnel].[ScrubShots], " _
& "tblMsnPers.Review = [tblPersonnel].[ReviewDate], " _
& "tblMsnPers.ATL1 = [tblPersonnel].[ATL1], " _
& "tblMsnPers.SERE = [tblPersonnel].[SERE], " _
& "tblMsnPers.CED = [tblPersonnel].[CED], " _
& "tblMsnPers.GTCexp = [tblPersonnel].[ScrubGTC] " _
& "WHERE ((tblMsnPers.MsnID = " & Me.ID & ") AND (tblMsnPers.EDIPI = '" & Me.PerSelect & "'));"
DoCmd.RunSQL SqlStr2
DoCmd.SetWarnings True
I can't help but feel like there's a better way to write the SQL string here because full disclosure, I have barely half a clue on what I'm doing here, being a student of reverse-engineering and Google-Fu. Is there a better way to write the SQL string here?
I would use this
Dim rstPerson As Recordset
Dim rst As Recordset
Dim strSQL As String
strSQL = "SELECT * from tblersonal where EDIPI = '" & Me.PerSelect & "'"
Set rstPer = CurrentDb.OpenRecordset(strSQL)
Set rst = CurrentDb.OpenRecordset("tblMsnPers")
With rst
.AddNew
!MnID = Me.ID
!EDIPI = Me.PerSelect
!NameStr = rstPer!NameStr
!PriAlt = Me.cmbPriAlt
!Errors = rstPer!ScrubErrors
!PT = rstPer!ScrubFitDate
!vRED = rstPer!ScrubvRED
!ISOPREP = rstPer!ISOPREP
![2760] = rstPer!Scrub2760
!Checklist = rstPer!ScrubStatus
!IMR = rstPer!ScrubShots
!Review = rstPer!ReviewDate
.Update
.Close
End With
This works well since:
All of the data type checking is done for you. (", strings, # dates,
none for numbers)
You don't have messy concatenation.
You get parameter safe code (no sql injection - at least for update part).
It much less code. Far more readable.
And if you convert the data base to sql server, the above code will continue to work.

VBA/SQL issue access

I keep recieving compiling errors saying that txtlln in the where line cannot be found. I am fairly new to SQL/VBA so I am not sure I am using the correct expressions to have this work.
Private Sub btnlledit_Click()
Dim strSQL As String
SQL = "UPDATE tblll " & _
"SET [Component/Product] = '" & Forms!frmaddll!txtllcomponent & "',[HN] = '" & Forms!frmaddll!txtllhn & "' " & _
"WHERE [LLN] = '" & Forms!frmaddll!txtlln.value & "';"
debug.print sql
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
DoCmd.Requery
Me.Refresh
End Sub
You seem to have a few issues swith your string concatenation.
Private Sub btnlledit_Click()
Dim strSQL As String
SQL = "UPDATE tblll " & _
"SET [Component/Product] = '" & Forms!frmaddll!txtllcomponent & "' " & _
"WHERE [LLN] = '" & Forms!frmaddll!txtlln.value & "';"
debug.print sql
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
DoCmd.Requery
Me.Refresh
End Sub

Apostrophe in memo text causing error in code

I am using Access 2016 and I am running into an error where a memo field gets updated and people are using apostrophes and it interferes with the code to update. The code works great and it updates the table for specific values unless there is an apostrophe present. No amount of parentheses or brackets have resolved this issue to isolate the apostrophes in text from the code. I would prefer suggestions that would I allow me to have apoostrophes if possible.
Private Sub btnlledit_Click()
Dim SQL As String
SQL = "UPDATE tblll " & _
"SET [LLN] = '" & Forms!frmaddll!txtlln & "',[REF] = '" & Forms!frmaddll!txtllref & "',[TRN] = '" & Forms!frmaddll!txtlltr & "',[HN] = '" & Forms!frmaddll!txtllhull & "', [LL] = '" & Forms!frmaddll!txtll & "',[CA] = '" & Forms!frmaddll!txtllca & "',[CP] = '" & Forms!frmaddll!txtllcomponent & "',[LOC] = '" & Forms!frmaddll!txtllloc & "',[LFSE] = '" & Forms!frmaddll!txtlllfse & "',[FC] = '" & Forms!frmaddll!txtllfc & "' " & _
"WHERE [LLN] = '" & Forms!frmaddll!txtlln.Value & "';"
DoCmd.RunSQL SQL
DoCmd.Requery
Me.Refresh
End Sub
I've cut down your SQL to give you an idea.
The first line of SQL are the parameters - note the ; at the end of the first line.
Private Sub btnlledit_Click()
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.CreateQueryDef("", _
"PARAMETERS LLN_Value TEXT(255), REF_Value TEXT(255), TRN_Value TEXT(255); " & _
"UPDATE tblll " & _
"SET LLN = LLN_Value, REF = REF_Value, TRN = TRN_Value " & _
"WHERE LLN = LLN_Value")
With qdf
.Parameters("LLN_Value") = Forms!frmaddll!txtlln
.Parameters("REF_Value") = Forms!frmaddll!txtllref
.Parameters("TRN_Value") = Forms!frmaddll!txtlltr
.Execute
End With
End Sub
A better way would be to move the execution of the query to another procedure and pass the required values to that:
Public Sub MyQuery(My_LLN_Value AS String, My_Ref_Value AS String, My_TRN_Value AS String)
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.CreateQueryDef("", _
"PARAMETERS LLN_Value TEXT(255), REF_Value TEXT(255), TRN_Value TEXT(255); " & _
"UPDATE tblll " & _
"SET LLN = LLN_Value, REF = REF_Value, TRN = TRN_Value " & _
"WHERE LLN = LLN_Value")
With qdf
.Parameters("LLN_Value") = My_LLN_Value
.Parameters("REF_Value") = My_Ref_Value
.Parameters("TRN_Value") = My_TRN_Value
.Execute
End With
End Sub
You can then call this procedure from your button click:
Private Sub btnlledit_Click()
MyQuery Forms!frmaddll!txtlln, Forms!frmaddll!txtllref, Forms!frmaddll!txtlltr
End Sub
Or from elsewhere, and getting your values from elsewhere to:
Public Sub Test
Dim Second_Arg AS String
Second_Arg = "Some Reference Value"
MyQuery Forms!frmaddll!txtlln, Second_Arg, "Third Argument"
End Sub
I said in a minute but had other stuff (+ writing this in VBA is a torture):
Dim SQL As String
SQL = "UPDATE tblll " & _
"SET [REF] = #ref,[TRN] = #trn,[HN] = #hn" & _
", [LL] = #ll,[CA] = #ca,[CP] = #cp,[LOC] = #loc " & _
", [LFSE] = #lfse, [FC] = #fc" & _
"WHERE [LLN] = #lln";"
Dim oConnection As ADODB.Connection
Dim oCommand As ADODB.Command
Set oConnection = New ADODB.Connection
Set oCommand = New ADODB.Command
oConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\MyFolder\MyData.accdb;"
oConnection.Open
oCommand.ActiveConnection = oConnection
oCommand.CommandText = SQL
oCommand.Parameters.Append oCommand.CreateParameter("#ref", adInteger)
oCommand.Parameters.Append oCommand.CreateParameter("#trn", adVarChar, adParamInput, 100)
oCommand.Parameters.Append oCommand.CreateParameter("#hn", adInteger)
oCommand.Parameters.Append oCommand.CreateParameter("#ll", adInteger)
oCommand.Parameters.Append oCommand.CreateParameter("#ca", adInteger)
oCommand.Parameters.Append oCommand.CreateParameter("#cp", adInteger)
oCommand.Parameters.Append oCommand.CreateParameter("#loc", adInteger)
oCommand.Parameters.Append oCommand.CreateParameter("#lfse", adInteger)
oCommand.Parameters.Append oCommand.CreateParameter("#fc", adInteger)
oCommand.Parameters.Append oCommand.CreateParameter("#lln", adInteger)
oCommand.Parameters("#ref" ).Value = Forms!frmaddll!txtref.Value
oCommand.Parameters("#trn" ).Value = Forms!frmaddll!txttrn.Value
oCommand.Parameters("#hn" ).Value = Forms!frmaddll!txthn.Value
oCommand.Parameters("#ll" ).Value = Forms!frmaddll!txtll.Value
oCommand.Parameters("#ca" ).Value = Forms!frmaddll!txtca.Value
oCommand.Parameters("#cp" ).Value = Forms!frmaddll!txtcp.Value
oCommand.Parameters("#loc" ).Value = Forms!frmaddll!txtloc.Value
oCommand.Parameters("#lfse").Value = Forms!frmaddll!txtlfse.Value
oCommand.Parameters("#fc" ).Value = Forms!frmaddll!txtfc.Value
oCommand.Parameters("#lln" ).Value = Forms!frmaddll!txtlln.Value
oCmd.Execute
This code is not specifically an access code but VBA (that you can execute from any VBA environment, say Excel, Word ...).
Since I don't know your fields, parameter types are just for sampling. The important thing here is, you have to define the parameters in the same order as they appear in your query string. After appending the parameters, you are free to set their values in any order you like (that is a limitation in driver I think, parameters are not named but positional).
NOTE: I dropped initial LLN= because you were searching for it and setting to the same value (IOW no change).
Single quotes are escaped by doubling them up, just as you've shown us in your example. The following SQL illustrates this functionality.
BTW, Go for SQL Parameter instead of these inline SQL Injection.
Try like below:
Private Sub btnlledit_Click()
Dim SQL As String
SQL = "UPDATE tblll " & _
"SET [LLN] = '" & Forms!frmaddll!txtlln & "',[REF] = '" & Forms!frmaddll!txtllref & "',[TRN] = '" & Forms!frmaddll!txtlltr & "',[HN] = '" & Forms!frmaddll!txtllhull & "', [LL] = '" & Forms!frmaddll!txtll & "',[CA] = '" & Forms!frmaddll!txtllca & "',[CP] = '" & Forms!frmaddll!txtllcomponent & "',[LOC] = '" & Forms!frmaddll!txtllloc & "',[LFSE] = '" & Forms!frmaddll!txtlllfse & "',[FC] = '" & Forms!frmaddll!txtllfc & "' " & _
"WHERE [LLN] = '" & Forms!frmaddll!txtlln.Value & "';"
Replace (SQL, "'", "''")
DoCmd.RunSQL SQL
DoCmd.Requery
Me.Refresh
End Sub

Updating Access Database using UPDATE SQL statement in VBA

Can someone take a look a the stSQL string and help me fix the syntax error I am getting associated with the UPDATE statement?
Run-time error '-2147217900 (8004e14)': Syntax error in UPDATE statement.
I have a rudimentary understanding of SQL and don't seem to understand where I have gone wrong.
I want to update the fields of Table 1 if the FileName UserForm value matches a FileName field in the Access Db.
Thanks
Public Sub UpdateDatabaseEntry()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim stDB As String, stSQL As String, stProvider As String
Dim FileName As String
Dim Nickname As String
Dim RecipientName As String
Dim RecipientRelationship As String
Dim Summary As String
Dim Noteworthy As String
Dim PreparedBy As String
FileName = UserForm1.FileNameTextBox.Text
Nickname = UserForm1.NicknameTextBox.Text
RecipientName = UserForm1.RecipientNameTextBox.Text
RecipientRelationship = UserForm1.RecipientRelationshipComboBox.Text
Summary = UserForm1.SummaryTextBox.Text
Noteworthy = UserForm1.NoteworthyCheckBox.Value
PreparedBy = UserForm1.PreparedByTextBox.Text
stDB = "Data Source= E:\MyDb.accdb"
stProvider = "Microsoft.ACE.OLEDB.12.0"
//Opening connection to database
With cn
.ConnectionString = stDB
.Provider = stProvider
.Open
End With
//SQL Statement telling database what to do
stSQL = "UPDATE Table1" & _
"SET Nickname= '" & Nickname & "', RecipientName= '" & RecipientName & "', " & _
"RecipientRelationship= '" & RecipientRelationship & "', Summary= '" & Summary & "', " & _
"Noteworthy= '" & Noteworthy & "', PreparedBy= '" & PreparedBy & "', " & _
"WHERE FileName= '" & FileName & "'"
cn.Execute stSQL
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
At least one problem is caused by lack of spaces in the query. So your query started UPDATE Table1set.
stSQL = "UPDATE Table1 " & _
"SET Nickname= '" & Nickname & "', RecipientName= '" & RecipientName & "', " & _
"RecipientRelationship= '" & RecipientRelationship & "', Summary= '" & Summary & "', " & _
"Noteworthy= '" & Noteworthy & "', PreparedBy= '" & PreparedBy & "'" & _
"WHERE FileName= '" & FileName & "'"
If this doesn't fix the problem. Then edit your question with the value of stSQL after the variable substitution.
EDIT:
As TS points out, another problem is the , before the where (fixed above).