How to insert in to MDB using vb.net? - vb.net

Dim MyInsert As String = "INSERT INTO Inventory(userid,
Type,Number) Values(" & _
txtEquipCat.text & "," & _
Type.Text & "," & _
Number.text & ")"
while executing this im getting
syntax error:Insert in to statement
error.
How to insert keywords like type and number in to MDB?
I want to specify the columnname while insert.

First of all, use parameters. Secondly, your string concoction isn't putting "quotes" around the text.
That is, VALUES ('" & txtEquipCat.Text & "',...
Don't try to fix it like that though.
Use parameters: VALUES (?, ?, ?)
cmd.Parameters.AddWithValue("?", txtEquipCat.Text)
Notice with parameters, you do not have to worry about any quotation marks. The parameters have to be entered in order, so the first "?" corresponds to txtEquipCat, the second to Type.Text, etc.

Related

using what I think is a variable in a SQL statement

I am very new to SQL and think I have a simple problem but was unable to figure it out from other posts. I have the following code:
INSERT INTO tblShortScores ( TradeNum, FilterNum, Rank, ScoreNum )
SELECT [Forms]![frmOpenTrades]![TradeNum] AS TradeNum, tblFilters.FilterNum, tblFilters.SBBExh AS Rank, tblFilters.SBBExh AS Score
FROM tblFilters
WHERE (((tblFilters.SBBExh) Is Not Null));
but instead of using the literal "SBBExh" in tblFilters.SBBExh, I want to do something like
tblFilters.("S" & [Forms]![frmOpenTrades]![Strategy])
where something like
[Forms]![frmOpenTrades]![Strategy] contains the value "BBExh".
It's in MS Access and I seem unable to find a syntax that works
any help is appreciated
Can't dynamically build field name in query object. Use VBA to construct and execute action SQL, like:
strField = "S" & Me.Strategy
CurrentDb.Execute "INSERT INTO tblShortScores (TradeNum, FilterNum, ScoreNum) " & _
"SELECT " & Me.TradeNum & " AS TradeNum, FilterNum, " & strField & " " & _
"FROM tblFilters WHERE " & strField & " Is Not Null;"
Assumes TradeNum is number type - if it is text, use apostrophe delimiters:
SELECT '" & Me.TradeNum & "' AS .
If SQL injection is a concern review, How do I use parameters in VBA in the different contexts in Microsoft Access?

SQL Statement to grab data from entry form to Data table in Microsoft Access 2010 VBA

So I'm setting up a database in MS Access 2010 (first time doing this). I can't seem to get the syntax of the SQL statement right. I want to take the data I have entered into a data entry form and insert a new row into a table, with that data. All of this using SQL in the VBA editor (only code I have available, all others are blocked)
Private Sub Add_Click()
Dim sSQL As String
sSQL = "INSERT INTO Data (Type, Name, Quantity, Amount, Class, Series, Client, Date1, Date2) VALUES " & _
"('" & Me!txtType & "','" & Me!txtName & "'," & Me!txtQuantity & "," & Me!txtAmount & ",'" & Me!txtClass & "','" & Me!txtSeries & "','" & Me!txtClient & "'," & Me!date1 & "," & Me!date2 & ")"
Debug.Print sSQL
CurrentDb.Execute sSQL
End Sub
So i Get the following error when i run the code, from the VBA editor :
"Run-time error '3134':
Syntax error in INSERT INTO statement."
And the printout of the SQL statement looks correct :
INSERT INTO Data (Type, Name, Quantity, Amount, Class, Series, Client, Date1, Date2)
VALUES ('Purhcase', 'TV', 500, 100, '', '', ' Bob', 05.08.2019, 05.08.2019)
Found the answer :
turns out one of the names of my data fields was a reserved word, therefore i simply put them all into [] and it solved the issue.
Thanks anyways for the help guys!

MS Access / SQL : error in insert query statement

I am using MS Access 1997 version (.mdb file). On a daily basis, I need to insert values manually. In that file, there's a column Logical (Boolean data type). I am automate this template using SQL query instead of direct entry.
Below is my insert query:
Insert Into Data_CustomerTransmit_Tbl (Logical)
Values (" & Logicalnme & ")
Values:
Logicalnme - True
When I run this query in VBA in Excel, I get this error message
Syntax Error in Insert into Statement
Kindly confirm shall I use "Logical" as column name or this is the reserved keyword?
Thanks in advance.
There isn't a problem with your field name, you just need to enclose your INSERT column name in square brackets. You also need to choose a valid value in the VALUES clause:
INSERT INTO Data_CustomerTransmit_Tbl ( [Logical] )
VALUES (TRUE);
If you want to be prompted for the value to insert, you can use a parameter:
PARAMETERS [Please enter a Boolean value] YesNo;
INSERT INTO Data_CustomerTransmit_Tbl ( [Logical] )
VALUES ([Please enter a Boolean value]);
I presume you are trying to do this insert using VBA? If so, your syntax in building the SQL statement is correct, except you have some punctuation missing: double-quotes on each end.
"INSERT INTO Data_CustomerTransmit_Tbl (Logical) VALUES (" & Logicalnme & ")"
Further, as you have split the string over two lines (breaking before VALUES), you must also terminate the first line of the string with: ' " & _' (space,double-quote,space, ampersand, space, underscore) in order to indicate that the string continues to the next line. Then you begin the next line with double-quotes:
"INSERT INTO Data_CustomerTransmit_Tbl (Logical) " & _
"VALUES (" & Logicalnme & ")"
In VBA the code should look like this:
Docmd.RunSQL("INSERT INTO Data_CustomerTransmit_Tbl (Logical) VALUES (" & Logicalnme & ");"
The SQL query you alluded to - have you tried to execute it manually in the query editor using the same value(s) you are trying to pass from Excel? That would immediately provide more verbose feedback if there is an issue with the query or the data.
Regarding the Boolean field, make sure you are receiving a True/False that you are expecting, not a bit field, 0 and 1. I like to make quick log entries in a table or a file when troubleshooting to see the raw data.
Use Cbool function:
Insert Into Data_CustomerTransmit_Tbl (Logical)
Values (" & Cbool(Logicalnme) & ")
Add single quotes around values?
sql = "INSERT INTO Data_CustomerTransmit_Tbl (Logical) " & _
"VALUES ('" & Logicalnme & "')"
docmd.runsql sql

Problem with executing an SQL insert statement in access using VBA

I'm trying this SQL statement but I keep getting an error
Run-time error '3061':
Too few parameters. Expected 4.
The statement I am trying to execute is:
sSQL = "INSERT INTO MasterTable (AdmissionNumber, Surname, Forename, TutorGroup) VALUES (intAdmissionNo, strSurName, strForeName, strTutorGroup)"
CurrentDb.Execute sSQL, dbFailOnError
The 4 values intAdmissionNo, strSurName, strForeName and strTutorGroup all have values and the fields all exist.
Any help is much appreciated, thanks! :)
I haven't done that from VBA, but unless I'm mistaken you're not sending in the variables as you think you are. Try this line instead of your current one:
sSQL = "INSERT INTO MasterTable (AdmissionNumber, Surname, Forename, TutorGroup) VALUES (" & intAdmissionNo & ", " & strSurName & ", " & strForeName & ", " & strTutorGroup & ")"

VBA select not returning any rows

Below query is not returning any rows into the listbox.There is no error message:
lstDiff.RowSource = "select TestScenario,TestId from tblTesting where empid= '" & Me.txtEmpId.Value & "' and testid= '" & Me.txtAutoNumber.Value & "'"
Could anyone help?
Your values in the field are numeric, so the extra single quotes aren't needed. Code should look like the following:
Me.lstDiff.RowSource = "select TestScenario,TestId from tblTesting where empid= " & Me.txtEmpId & " and testid= " & Me.txtAutoNumber & ";"
I've also dropped .Value from the field references, they're not harmful, but also aren't necessary.
And I've added a semi-colon to the end of your statement.
Depending on when/where you insert this code, you may need to add the following statement as well:
Me.lstDiff.Requery
You keep posting questions about the exact same WHERE clause with exactly the same apparent error in each one. SO users dutifully point out your error and then a few days later, you show up with a related question utilizing the same faulty WHERE clause.
DLookup Problem:
txtContSunStart1.Value = DLookup("Start1", "tblContract", _
"TestId = " & _
lstResults.Value & _
"" And "Day = 'Sunday'")
VBA Update Query:
DoCmd.RunSQL (" Update tbltesting set IsDiff ='Yes' where empid= " & Me.txtEmpId.Value & " and testid= " & Me.txtAutoNumber.Value & ";")
VBA SQL Problem
DoCmd.RunSQL ("insert into tbltesting (IsDiff)values ('Yes') where empid= '" & Me.txtEmpId.Value & "' and testid= '" & Me.txtAutoNumber.Value & "'")
And then in the current question:
lstDiff.RowSource = "select TestScenario,TestId from tblTesting where empid= '" & Me.txtEmpId.Value & "' and testid= '" & Me.txtAutoNumber.Value & "'"
You are having difficulties with exactly the same set of problems repeatedly.
Here are the rules for concatenating SQL strings with the correct delimiters in Access:
numeric values do not need delimiters:
"... AND testid= " & Me!txtAutoNumber
text values need quote delimiters. In Access, it's general practice to use double quotes, but much easier to use single quotes since it's a pain to type double quotes in a form that will work (typing """ or """" depending on context is counterintuitive and silly to me, so I always define a global constant that holds the double quote symbol and concatenate with that).
"... AND textfield=" & Chr(34) & Me!MyTextField & Chr(34)
date values use the # delimiter:
"... AND datefield=#" & Me!MyDateField & "#"
Boolean fields require no quotes and it works best to use True and False:
"... AND IsDiff=True"
These rules apply both to WHERE clause criteria and to SET statements in UPDATE queries. The rules apply in writing a SQL string that you pass to DoCmd.RunSQL or CurrentDB.Execute, as well as to writing SQL strings to be used as the recordsource of a form or report or as the rowsource of a combo box or listbox.
Personally, whenever I use SQL statements in code, I prefer to store the statement in a variable. While testing, on the line after you assign your statement to a variable, you can use Debug.Print to see what your SQL statement looks like after parsing your txtempid and txtautonumber. It would look something like this.
Dim sSQL as String
sSQL = "select TestScenario,TestId from tblTesting where empid= '" & Me.txtEmpId.Value & "' and testid= '" & Me.txtAutoNumber.Value & "'"
Debug.Print sSQL
lstDiff.RowSource = sSQL
Then as long as your immediate window is visible (Ctrl-G), you can see what your SQL statement really is. If it looks right in the immediate window, copy and paste it into the query builder and run it there.
Try running the query in your SQL Management Studio. Do you get any row(s) back?
Edit: Just noticed the access-tag. Are you sure your table contains at least one post with supplied ids?
My Access is a bit rusty, but if all else fails try using a recordset to capture the data from the SQL and loop through it adding the values to the list box. Example Code