vbScript - InputBox into .accdb , blank? - sql

After 9 hours of research and trial and error, I've come to all of you with this current issue I am having with another script I wrote to input data into a database. I'll simplify the focal point of this problem in the code view. I have 3 fields, one is a timestampe at the end of the SQL such as .... & now() & "')". That inserts FIND, but by variable inputboxes insert blank data.
Option Explicit
Dim ib
Dim sql1, constring, con
constring="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\users\user\documents\database1.accdb;"
sql1="INSERT INTO table1 (column1) VALUES('" & ib & "')"
set con = createobject("adobd.connection")
con.open constring
Do
ib=inputbox("Input Data")
IF ib="quit" OR ib="QUIT" THEN
con.close
ELSE con.execute sql1
End If
Loop WHILE ib<>"quit" AND ib<>"QUIT"
It is appending rows into the database, but they are blank. Ive designed the table to take short text of <255 chars.
I also ran a test query from within the database and it inserts what I tell it to, but the inputbox data, for some reason, is not making it to the table.

This
sql1="INSERT INTO table1 (column1) VALUES('" & ib & "')"
concats an (empty) ib into sql1 before the loop. con.execute sql1 will insert that into the database until you quit.
Try
con.execute "INSERT INTO table1 (column1) VALUES('" & ib & "')"
and optimize when it works.

Do
ib=inputbox("Input Data")
If LCase(ib) <> "quit" THEN
con.execute "INSERT INTO table1 (column1) VALUES('" & ib & "')"
End If
Loop WHILE ib<>"quit" AND ib<>"QUIT"
con.close
You need to recreate the string that you will execute for each value that you retrieve

Related

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!

VBA Excel SQL INSERT query adds apostrophe to all data inserted

I'm trying to use an INSERT statement to insert data from a userform to an excel spreadsheet, but it adds apostrophes to every inserted value, even dates and numbers.
How can I do an insert statement that will not insert any apostrophe for any value?
Code I'm using currently:
Sub Insert_data()
Dim con As Object
Dim vSQL1 As String
Dim dbpath As String
dbpath = myworkbookpath
Set con = CreateObject("ADODB.Connection")
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbpath & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=0"";"
con.Open
'CancelledFeeEntryForm.LogDate.Value = Date
'CancelledFeeEntryForm.RecordAppNum.Value = 123456789
vSQL1 = "INSERT INTO [Sheet1$] ([Employee],[Date Of Call],[Application Number]) " & _
"VALUES('" & CancelledFeeEntryForm.Employee.Value & "'," & _
"#" & CancelledFeeEntryForm.LogDate.Value & "#," & _
CancelledFeeEntryForm.RecordAppNum.Value & ");"
con.Execute (vSQL1)
con.Close
End Sub
You should've debugged and looked at what exactly vSQL1 is containing.
From looking at it, this is what your SQL statement is going to look like:
... VALUES ('SomeStringValue',#SomeDateValue,123')
... aka, there's an apostrophe at the end of the numerical value... but not at the beginning.
To be honest, I'm glad Excel VBA is handling it like this. Because the alternative would be having an open security hole for SQL Injection Attack (I was about 5 seconds away from going on a rant about how you should never do SQL statements like this, until I noticed that VBA protected you from a serious security mistake.)
Figured out a work around, although it's annoying, it'll have to do for now.
As is with excel in many cases, I had to enter dummy data on line 2 of the workbook i'm inserting data in the format I want. Then, when using the SQL insert code, it will match the existing data.
If anyone knows how to do it through code, feel free to pitch in. thanks

Syntax Error in INSERT INTO Statement (Error 3134)

I'm using MS Access 2013. My current issue is with the following code, I use to log user activity.
Table is called: tbl-activitylog and has five columns :
id
timestamps
Username
Activity
Additional
I checked code many times char after char and don't know what's wrong :(
TempVars("UserName").Value = "admin"
Logging("Logon", "system")
Public Sub Logging(Activity, Additional As String)
Dim sql_code As String
sql_code = "INSERT INTO tbl-activitylog(Username, Activity, Additional) VALUES('" & TempVars("UserName").Value & "','" & Activity & "','" & Additional & "')"
Debug.Print sql_code
CurrentDb.Execute sql_code
End Sub
Debug print shows:
INSERT INTO tbl-activitylog(Username, Activity, Additional) VALUES('admin','Logon','System')
Becaus of using "-" you have to do it in this way [tbl-activitylog]
sql_code = "INSERT INTO [tbl-activitylog](Username, Activity, Additional) VALUES('" & TempVars("UserName").Value & "','" & Activity & "','" & Additional & "')"
This 3134 error denotes a syntax error in your INSERT statement. As the name of your table contains a dash, you need to enclose it between brackets :
INSERT INTO [tbl-activitylog]
(Username, Activity, Additional)
VALUES('admin','Logon','System')
Generally speaking you may as well enclose all fields and table names, to avoid all risks of clashes with ms-access reserved words, like :
INSERT INTO [tbl-activitylog]
([Username], [Activity], [Additional])
VALUES('admin','Logon','System')
Consider a parameterized query, an industry best practice in any application layer language running SQL in any database. With QueryDefs, you can parameterize queries in MS Access.
Even more MS Access will not allow you to save queries with syntax issues. So, be sure to escape special characters and reserved words with square brackets or backticks.
SQL (save below as a query object)
PARAMETERS UsernameParam Text, ActivityParam Text, AdditionalParam Text;
INSERT INTO [tbl-activitylog] ([Username], [Activity], [Additional])
VALUES ([UsernameParam], [ActivityParam], [AdditionalParam])
VBA (reference above query and bind values without quotes or concatenation)
TempVars("UserName").Value = "admin"
Logging("Logon", "system")
Public Sub Logging(Activity, Additional As String)
Dim sql_code As String
Dim qdef As QueryDef
Set qdef = CurrentDb.QueryDefs("mySavedQuery")
' BIND PARAMS
qdef![UsernameParam] = TempVars("UserName")
qdef![ActivityParam] = Activity
qdef![AdditionalParam] = Additional
qdef.Execute dbFailOnError
Set qdef = Nothing
End Sub

SQL statement in VBA

I am trying to run the following SQL statement in ACCESS 2013 VBA but am getting errors due to wrong formatting (in this case I get "Semicolon (;) missing from end of statement"). Could anybody tell me what I am doing wrong in the code below please?
Dim dbs As dao.Database
Set dbs = CurrentDb()
dbs.Execute "INSERT INTO TEMP2 ([Study_Date], [Created_By], [Part_Number],
[Upper_Tolerance], [Lower_Tolerance], [ID21_Number]) VALUES ([Study_Date],
[Created_By], [Part_Number], [Upper_Tolerance], [Lower_Tolerance], [ID21_Number])
FROM RAC_DATA_ENTRY
WHERE [RAC_CAP_VALS] = '" & Me.[RAC_CAP_VALS] & "'"
Don't use VALUES when you're pulling data from one table to INSERT into another. Use SELECT instead.
This example uses just two of your fields. Add in the others you need.
Dim strInsert As String
strInsert = "INSERT INTO TEMP2 ([Study_Date], [Created_By])" & _
" SELECT [Study_Date], [Created_By] FROM RAC_DATA_ENTRY" & _
" WHERE [RAC_CAP_VALS] = '" & Me.[RAC_CAP_VALS].Value & "';"
Debug.Print strInsert '<- view this in Immediate window; Ctrl+g will take you there
dbs.Execute strInsert, dbFailOnError
Notes:
A semicolon at the end of the statement is optional. Access will consider the statement valid with or without it.
Value is not actually required following Me.[RAC_CAP_VALS], since it's the default property. I prefer to make it explicit.
dbFailOnError gives you better information about failed inserts. Without it, a problem such as a primary key violation would fail silently.
Debug.Print strInsert allows you to inspect the statement you built and are asking the db engine to execute. If there is a problem, you can copy the statement text from the Immediate window and paste it into SQL View of a new Access query for testing.

cannot insert datetime in visual basic

I have one question and was wondering if someone could help..
I have created a program in vb net. When I press a button then it should insert in my sql database in the column "date" the current date and time. I use for this purpose the following code :
query1 = "insert into visit(visit,textfile,p_id) VALUES('" & Date.Today & "','" & s & "',(select patient.p_id from patient where (patient.name=('" & ComboBox1.Text & " '))))"
Well it does its job but when i look in my database in the column 'visit' it displays only zeros.
Any ideas?
Use a parameterized query (this example is for Sql Server). In this way you don't need to worry how to quote a date, a string or what is the correct decimal separator required by the database.
Moreover you avoid any problem with Sql Injection attacks
query1 = "insert into visit(visit,textfile,p_id) VALUES(#p1, #p2, " & _
"(select patient.p_id from patient where patient.name=#p3)"
Dim cmd As MySqlCommand = new MySqlCommand(query1, connection)
cmd.Parameters.AddWithValue("#p1", Date.Today)
cmd.Parameters.AddWithValue("#p2", s)
cmd.Parameters.AddWithValue("#p3", ComboBox1.Text)
cmd.ExecuteNonQuery()