saving data from form to table in access - ms-access

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.

Related

Running an SQL string in VBA?

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.

strSQL formatting in Access

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

Insert statement in access gives error

I have been working on creating an extremely simple database with only 4 tables and only a few pieces of information per column. One of my tables is called "Customer" and inside of this table there or 4 columns for information.
I have a button on my "AddCustomerForm" that runs the following command
Private Sub cmdadd_Click()
CurrentDb.Execute "INSERT INTO Customer(Customer ID, Email, Identifier) " & _
= VALUES(Customer ID, Email, Identifier)
End Sub
My Add customer form looks like this:
Could someone please point out what I am messing up? The error I receive is :
Syntax error.
There's a few issues I see - is [Customer ID] an autonumber field? If so don't include it.
Also - if you're running a Manual Insert I assume your form is NOT bound to your table, though I begin to wonder why Customer ID is shown on the form as being editable?
Finally it looks like Location is a numeric ID belonging to ID field of the Location dropdown that fills in the Business ID field
This will help you debug your SQL and show us what's wrong
Add it to your button and show us the value shown in Immediate Window when the code halts
Dim strSQL as string
strSQL = "INSERT INTO Customer ([Customer ID], Email, Identifier) VALUES (" _
& me.[Customer ID] & ",""" & Me.[Email] & """,""" & Me.[Identifier] & """)"
Debug.print strSQL
CurrentDb.Execute strSQL
If Customer ID is AutoNumber try this instead (assuming form is UNBOUND) and Location is ID value of first column of dropdown
Dim strSQL as string
strSQL = "INSERT INTO Customer (Email, Identifier) VALUES (" _
& me.[Customer ID] & ",""" & Me.[Email] & """, & Me.[Identifier] & ")"
Debug.print strSQL
CurrentDb.Execute strSQL
Private Sub cmdadd_Click()
CurrentDb.Execute "INSERT INTO Customer ([Customer ID], Email, Identifier) VALUES([Forms]![MyFormName]![CustomerIDTextboxName], [Forms]![MyFormName]![EmailtextboxName], [Forms]![MyFormName]![IdentifierTextboxName]);"
End Sub
Access requires brackets around any field name with a space. I also deleted the = before VALUES and changed the values to reference your form controls, which you will have to name appropriately. You also need a semi-colon to complete the statement and need to close your double-quotes.
This page might help with syntax.

currentdb execute does not insert

I'm having trouble with Access VBA. I made the following code to insert some data to my SQL DB.
Private Sub btnFilmKijkenKlant_Click()
CurrentDb.Execute "INSERT INTO watchhistory (movie_id, customer_mail_address, watch_date, price, invoiced) VALUES (" & movie_id.Value & ", '" & Me.txtEmail & "', Date(),'" & price.Value & "', '0')"
End Sub
When the user hits the button I want some data to be transferred to the DB.
I don't get any errors but it just doesn't insert...
I made txtEmail field for testing. I got an e-mail field in another form that I want to use as customer_mail_address.
When I include the dbFailOnError option with CurrentDb.Execute, Access complains "ODBC Call failed", but I don't understand why.
Dim db as Database
Set db = CurrentDb()
db.execute(......)

Escaping unwanted characters, mainly single quotes --replace function and implementation

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.