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.
Related
Iv created the SQL string sql in ms access vba but when it runs it prints the string in the debug window but doesn't actually run the string to add a record to the table like I want it to.
Public Sub EmpoyeesTable_Click()
Dim sql As String
sql = "INSERT INTO Employees " & _
"VALUES " & "(1, 'James', 'Dan', 'n6 indro Rd', 0943747, 30.24);"
Debug.Print sql
End Sub
Ultimately I want to use SQL strings to take input from a form when submit is clicked and add it to a table? Is this even the right approach?
There are many ways to run SQL strings in VBA. Each have their own advantages, and disadvantages. The most common ones are:
DoCmd.RunSQL sql
Runs the SQL just as it would if you executed a query. Popup will occur when you add, delete or modify records. You can use UDFs and form parameters
DoCmd.SetWarnings False
DoCmd.RunSQL sql
DoCmd.SetWarnings True
Disables warnings, then runs the SQL like in the previous way, then sets warnings back on.
CurrentDb.Execute sql
Executes the SQL over a DAO connection to the current database. You can't use UDFs and form parameters here. No warnings are shown. It just executes the SQL.
CurrentProject.Connection.Execute sql
Executes the SQL over an ADO connection to the current database. Very similar to the DAO connection, but there are subtle differences. For example, you can execute DDL statements that contain the Decimal data type, and set Check constraints in this way, while both are not allowed in any of the other ways.
You can read about using parameters with these different ways here. That's strongly recommended if you are going to insert values that aren't constant, to avoid bugs and SQL injection.
If you think simply then just change your Debug.Print sql to DoCmd.RunSQL (sql)
Private Sub Command0_Click()
Dim sql As String
sql = "INSERT INTO Employees " & _
"VALUES " & "(1, 'James', 'Dan', 'n6 indro Rd', 0943747, 30.24)"
DoCmd.RunSQL (sql)
End Sub
If you want take values from form then refer each value from form control like text box. See the below codes.
Private Sub Command0_Click()
Dim sql As String
sql = "INSERT INTO Employees VALUES (" & _
"'" & Me.Text1 & "'," & _
"'" & Me.Text2 & "'," & _
"'" & Me.Text3 & "'," & _
"'" & Me.Text4 & "'," & _
"'" & Me.Text5 & "'," & _
"'" & Me.Text6 & "');"
DoCmd.RunSQL (sql)
End Sub
If the field value is number type the you can remove singe quote (') from code for those field.
I am having some trouble formatting an SQL string in Access, I can never seem to debug these syntax issues with SQL strings. I have this string:
strSQL = "SELECT * FROM FXData WHERE ShortCode=" & Forms!FXVolatility.cboCurve.Value & " AND MaxOfMarkAsOfDate=#" & MaxOfMarkAsofDate & "# ORDER BY MaxOfMarkAsOfDate "
debug.print strSQL
Set rs = CurrentDb.OpenRecordset(strSQL, Type:=dbOpenDynaset, Options:=dbSeeChanges)
which prints
SELECT * FROM FXData WHERE ShortCode=USD.XS AND MaxOfMarkAsOfDate=#3/31/2016# ORDER BY MaxOfMarkAsOfDate
However this gives me a "Too Few Parameters, expected 1" error.
All the fields and their associated values that are referenced in strSQL exist in the referenced table. What could the error be?
Also if you've got any resources on how to debug/identify these specific access SQL formatting issues I'd be happy to hear them.
In SQL, strings need to be put in single or double quotes. Thus, your output should look like this:
... WHERE ShortCode='USD.XS' ...
Thus, your code becomes:
strSQL = "SELECT * FROM FXData WHERE ShortCode='" & _
Replace(Forms!FXVolatility.cboCurve.Value, "'", "''") & _
"' AND MaxOfMarkAsOfDate=#" & MaxOfMarkAsofDate & _
"# ORDER BY MaxOfMarkAsOfDate "
The Replace ensures that any single quotes occurring within cboCurve.Value are properly escaped.
Note that it is recommended to use parameters instead of string concatenation to "fill" values into an SQL statement. An example for how to do this in MS Access can be found in the answer to this question:
VBA OpenRecordset Producing Too few parameters. Expected 2. Error
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 have a form, and I want to fill it, and then save some of the fields into an existing table called Order.
I'm trying to do this with this line of code:
CurrentDb.Execute "INSERT INTO Order (OrderNumber)" & " VALUES (' " & Me.order & " ')"
I have also tried it like this
CurrentDb.Execute "INSERT INTO Order (OrderNumber)" & " VALUES ( " & Me.order & " )"
but it doesn't seem to make a difference. I keep getting the following error:
run-time error '3134': syntax error in INSERT INTO statement.
what am I doing wrong?
Order is a reserved word. If you must keep that as the table name, bracket it to avoid confusing the db engine.
Dim strInsert As String
strInsert = "INSERT INTO [Order] (OrderNumber) VALUES ('" & Me.order & "')"
Debug.Print strInsert
CurrentDb.Execute strInsert, dbFailOnError
If OrderNumber is numeric data type instead of text, discard those single quotes from the INSERT statement.
Store your statement in a string variable. Then use Debug.Print to examine the completed statement you're asking the engine to execute. You can view the Debug.Print output in the Immediate window. Go there with Ctrl+g Copy the statement and paste it into SQL View of a new Access query for troubleshooting.
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.