I have a table with 4 columns and update them through excel user form and all are varchar (255). when I try to enter the character ' I get syntax error, mysql doesn't accept it... What am I doing wrong here, do I need to change datatype
Update: I figured that the problem is not with MySQL (obviously :) ) but my code to update the table.
Dim sq As String
sq = "UPDATE sample.`nov-21` SET `Site work being carried out`='" & sitecombo.value & "',`Group`='" & eqgrp.value & "',`Description`='" & desc.value & "',`T Number`='" & tn.value & "', WHERE sample.`nov-21`.`ID`= " & Me.IDnum & ";"
Escape ' with \ or another ': 'O''Malley' or 'O\'Malley'
When you write 'O'Malley', MySQL read string literal 'O' followed by name Malley (which is not recognized) and a ' with no meaning, hence the syntax error.
Related
Getting the error data type conversion error running this code.
the data is from text boxes set to data type rich text.
CurrentDb.Execute "UPDATE tblISPServices", "SET Location=& Me.cboLocation,ServiceType = & Me.cboSType, BBProvider = & Me.txtBBProvider" & "WHERE ID= & Me.txtID.Tag"
please help
Remember to get variable or control values from the VBA code and rest should be string inside double quotes.
When generating such SQL statement to execute remember 3 rules
1) String data type fields should have single quote for string value so I had put single quote before & after location for e.g. '" & Me.cboLocation & "'
2) Number data type do not need single quote, so remove single quote for ID field for e.g. ID= " & Me.txtID.Tag
3) Date data type will have # instead of single quote for e.g. #" & Now() & "#
My assumption is , in the table tblISPServices field Location is Text Data type, ServiceType is Text data type, DBProvider is Text data type and ID is Numeric.
Observe how I made changes to get variable(control property) from VBA to generate String variable.
CurrentDb.Execute "UPDATE tblISPServices SET Location= '" & Me.cboLocation & "', ServiceType = '" & Me.cboSType & "', BBProvider = '" & Me.txtBBProvider & "' WHERE ID= " & Me.txtID.Tag
Note : remember while generating such string make sure you do not join any keyword to string or number for e.g. following is wrong SQL since it does not separate where
BBProvider = '" & Me.txtBBProvider & "'WHERE ID= " & Me.txtID.Tag
Correct SQL would be,
BBProvider = '" & Me.txtBBProvider & "' WHERE ID= " & Me.txtID.Tag
So i'm trying to make a phonebook for my project. I can't seem to get the update code. It keeps on returning the error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1. Which I already know.
Why is it not possible to update only one column?
I have columns: name, tel#, mobile#, address
Here's my code for updating my selected column that returns the error
Dim sqlvalue As String = "update entries set Tel. # =
('" & txtNewTel.Text & "') where name = '" & txtName.Text & "'"
You need to enclose your field name Tel. # in backticks so MySQL will recognize this is a field and not some nonsensical formula or string.
Dim sqlvalue As String = "UPDATE entries SET `Tel. #` = '" & txtNewTel.Text & "' WHERE `name` = '" & txtName.Text & "'"
I also added backticks around the field name since that is often times a protected key word. Better safe than sorry.
I'm using Replace function in SQL query, it is working in access sql query design mode but not working in access VBA. Throwing expected end of statement. I tried all the ways but not working. CM column has a string like this ;#WR_1;#WR_2;#WR_3;#WR_4;# and I'm trying to get value WR_2 where ever the string occurs in CM column
strSQL = "SELECT * FROM WT_table " & _
"WHERE [CM] IS NOT NULL " & _
"AND (';' & Replace([CM], '#', "") & ';') Like '*;WR_2;*'; ;"
Just remove the second semi-colon (;) from the end of the last line - you have two of them, making it appear that there are multiple statements to be executed.
"AND (';' & Replace([CM], '#', "") & ';') Like '*;WR_2;*';"
In addition, as pointed out by simoco, you have a pair of double-quotes in your Replace function. I'm not certain whether you mean to have two single-quotes or not, but this would be the right code to use in that case:
"AND (';' & Replace([CM], '#', '') & ';') Like '*;WR_2;*';"
running a vb application with the following code. I keep getting an error on my 'INSERT INTO' sql query, can anyone see what im doing wrong? This is the error - Syntax error in INSERT INTO statement.
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\Dave\Documents\joblist.mdb;"
connection = New OleDb.OleDbConnection(connetionString)
Sql = "INSERT INTO jobList (StaffID, staffName, staffLastName, note, fault, section, techID, jobcomplete) VALUES ('" & staffid & "','" & staffFN & "','" & staffLN & "','" & staffNotes & "','" & staffFault & "', '" & staffSection & "', '" & techId & "','" & ava & "')"
connection.Open()
oledbAdapter.UpdateCommand = connection.CreateCommand
oledbAdapter.UpdateCommand.CommandText = Sql
oledbAdapter.UpdateCommand.ExecuteNonQuery()
connection.Close()
Me.JobListTableAdapter.Fill(Me.JoblistDataSet2.jobList)
Note and Section are reserved words in Jet SQL
You need to encapsulate them with square brackets
Sql = "INSERT INTO jobList (StaffID, staffName, staffLastName, [note], fault, " +
"[section], techID, jobcomplete) VALUES (......)"
This is the source of you syntax error, but .....
aside from that, you have many problems here:
As pointed out by Tim Schmeiter, you use the update command instead of
insert command.
you concatenate input text from your user to form an sql string. This
leads to sql injection attacks and problems in correct parsing of text
(apostrophes, invalid dates, invalid numbers, etc)
staffID and techID seems to be numeric fields in the database, but
you put their values inside single quotes like strings. If they are
numerics you will get another possible error there.
I assume you should use the InsertCommand instead of the UpdateCommand property since you are inserting.
oledbAdapter.InsertCommand.CommandText = "INSERT INTO jobList (StaffID, staffName, ....
Note that you're open for SQL-Injection and should use Parameters instead. You should also use Using statement to ensure that the connection gets closed even on error.
I was just testing my database and I realized that I run into problems wherever a text entry in my database contains a ' character (single quote). My solution for now is that before any .execute operations on a string, I call escape(string, "'", " "'" ").
Summarized example below:
qr = "INSERT INTO tblExample VALUES ( " & "'" & me.testparam & "'" & ");"
qr = Replace(qr, "'", " "'" ")
db.execute qr
'also tried qr = "INSERT INTO tblExample VALUES ( " & "'" & replace(me.testparam,"'"," ") & "'" & ");"
This was what I assumed to be the correct workaround to prevent errors from values such as Tourette's.
There's two problems with this. First of all, it's not working. Second, I have over 50 locations in code throughout my app where I call the statement db.execute qr where qr is a string that could potentially contain a single quote. I need the field in the table to contain the single quote, so I can't just replace it with a space or something similar.
Two part question:
Is there a better solution than going through all of my code calling Replace on every string that is to be executed as a query?
Why is my current implementation failing? - I still get syntax error in query expression even when escaping the single quote to a space.
First examine these 2 lines.
"VALUES ( " & "'" & me.testparam & "'" & ");"
"VALUES ( '" & me.testparam & "');"
Both will produce the exact same string. The difference for me is that my brain comprehends the second version faster.
Now, here is what the comments are telling you to do ... replace each single quote in your source string with two single quotes. I added Debug.Print so you can view the finished string in the Immediate window (go there with Ctrl+g) ... you can then see the actual string rather than trying to imagine what it looks like.
qr = "INSERT INTO tblExample VALUES ( '" & _
Replace(Me.testparam, "'", "''" & "');"
Debug.Print qr
db.Execute qr, dbFailOnError
Since I assumed db is a DAO.Database object variable, I included the dbFailOnError option. You should include an error handler in your code to deal with any problems dbFailOnError exposes.
When you run into trouble with a VBA function in a query, drop to the Immediate window and test your function expression there. This one triggers a compile error, "Expected: list separator or )":
? Replace("Tourette's", "'", " "'" ")
But this one works:
? Replace("Tourette's", "'", "''")
Tourette''s
I mentioned that because it's useful in general, and also because your title starts with "Escaping unwanted characters, mainly single quotes". So if you want to remove/replace other characters, not just single quotes, experiment in the Immediate window until you find a Replace() expression which works. Then use that expression in your query.
For example, if unwanted characters include line breaks ...
MyString = "foo" & vbCrlf & "bar" : ? MyString
foo
bar
? Replace(MyString, Chr(13) & Chr(10), " ")
foo bar
Note: I used Chr(13) & Chr(10) rather than vbCrlf as the find target because the db engine can use the Chr() function but doesn't know about the named constant (vbCrlf).
Your query is failing because you have not said where to insert :
Dim qd As QueryDef
qr = "INSERT INTO tblExample (AText) VALUES ( [avalue] );"
Set qd = CurrentDB.CreateQueryDef("",qr)
qd.Parameters("avalue").Value = me.testparam
qd.Execute dbFailOnError
Another method is to define a quote as constant (Const Quote = """") and use that to build SQL Statements. It is not possible to define a quote as Const Quote = Chr(34) as a constant definition can't be based on a function so one has to use four double quotes in a row. The third quote is what you are saving, the second quote is to excape the third quote and the first and last quote are because the value you are assigning is a string.
You will then be able to build SQL statements such as:
SQL = SELECT * FROM tblSyndromes
WHERE Syndrome = " & Quote & "Tourette's" & Quote & ";"
It will no longer matter that there are single quotes in your data.
I don't use parameters as if I upscale my database to sql server and convert my queries to pass-through queries, I can't use parameters. I rarely upscale but I write all my code with that assumption. Also if your query is not working as expected, how do find out what went wrong. If I have a variable called SQL, then I can always print the SQL statement and run it in a new query to see what it does.