I have been searching around for the proper way of connecting into the database(MS ACCESS 2007) using VB6.0... The problem is it says an error that "SYNTAX ERROR IN INSERT INTO STATEMENT"
DECLARATION CODE:
Dim adoConn As New ADODB.Connection
Dim adoRS As New ADODB.Recordset
Dim conStr, sqlStr As String
CONNECTION CODE:
conStr = "Provider=Microsoft.Jet.OLEDB.3.51;Data Source= " & App.Path & "\curriculum.mdb;Persist Security Info=False"
Set adoConn = New ADODB.Connection
adoConn.ConnectionString = conStr
adoConn.Open
Here is the BUTTON code:
sqlStr = "INSERT INTO cur(CourseCode, Units, Days, Time, RoomNumber, Instructor, Course, YearLevel, Term) VALUES ("
sqlStr = sqlStr & "'" & txtCurCourseCode.Text & "',"
sqlStr = sqlStr & "'" & txtCurUnits.Text & "',"
sqlStr = sqlStr & "'" & txtCurDays.Text & "',"
sqlStr = sqlStr & "'" & txtCurTime.Text & "',"
sqlStr = sqlStr & "'" & txtCurDays.Text & "',"
sqlStr = sqlStr & "'" & txtCurRoom.Text & "',"
sqlStr = sqlStr & "'" & txtCurInstructor.Text & "',"
sqlStr = sqlStr & "'" & cboCurCourse.Text & "',"
sqlStr = sqlStr & "'" & txtCurYearLevel.Text & "',"
sqlStr = sqlStr & "'" & txtCurTerm.Text & "')"
adoConn.Execute sqlStr
THE ERROR IS FOUND IN THIS LINE OF CODE WHEN I CLICK DEBUG: adoConn.Execute sqlStr
YOUr help would be greatly appreciated as this school project is needed by tomorrow. Been sleepless for many nights. thansk
Unfortunately, you are using duplicate value..
I mean yor are trying to INSERT INTO to 9 columns(CourseCode, Units, Days, Time, RoomNumber, Instructor, Course, YearLevel, Term), however, you are putting 10 values().
txtCurDays is duplicated.
That error indicates the generated SQL statement has an error in it.
Set a breakpoint on the line:
adoConn.Execute sqlStr
Then view the SQL query (print it to the immediate window or just examine it in the locals window). Check for any syntax errors.
One likely errore in your SQL would be a apastrophe (') in one of your text fields. You need to make sure you "escape" any apostrophes in your SQL statement. You can do this easily by tweaking your code a bit like so:
sqlStr = sqlStr & "'" & Replace(cboCurCourse.Text, "'", "''") & "',"
Escape the column names that match reserved words: TIME by enclosing in []:
sqlStr = "INSERT INTO cur(CourseCode, Units, Days, [Time], RoomNumber, Instructor, Course, YearLevel, Term) VALUES ("
You should also use paramaterized queries as what you have in vulnerable to SQL Injection. (Run with a ' in one of the textboxes)
Related
I'm trying to run a loop through a table that takes relevant information and then inserts it into a VFP9 .dbf table. However, I keep getting an automation error ('-2147217913 (80040e07)'). It seems to run the first time just fine, inserting into a table a single time before erroring out. I've made it print out the string every time with the execution part of the code commented out, but the SQL looks perfectly fine. What is the issue here?
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
sConnString = "DSN=Visual FoxPro Tables;UID=;SourceDB=s:\accounting\db;SourceType=DBF;Exclusive=No;BackgroundFetch=Yes;Collate=Machine;Null=Yes;Deleted=Yes;"
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open sConnString
For i = 1 To [RawTable].Rows.Count
vStatement = "dong!"
vAccount = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("account").Index)
vCardUser = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("card member").Index)
vDate = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("date").Index)
vDesc = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("description").Index)
vAmount = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("amount").Index)
MsgBox "INSERT INTO amex_dist (Statement,Account,Card_user,Date,Desc,Amount) VALUES ('" & vStatement & "','" & vAccount & "','" & vCardUser & "','" & vDate & "','" & vDesc & "'," & vAmount & ")"
conn.Execute ("INSERT INTO amex_dist (Statement,Account,Card_user,Date,Desc,Amount) VALUES ('" & vStatement & "','" & vAccount & "','" & vCardUser & "','" & vDate & "','" & vDesc & "'," & vAmount & ")")
Next i
MsgBox "done :)", vbInformation
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
EDIT: Here is an example of what the table will look like.
date receipt description card member account # amount account
07/01/2016 Purchase Employee XXXX-XXXXXX-XXXXX 9.95 41000-000-00
07/01/2016 Purchase Employee XXXX-XXXXXX-XXXXX 33 41000-000-00
06/29/2016 Purchase Employee XXXX-XXXXXX-XXXXX 64 41000-000-00
Visual Foxpro doesn't like receiving dates as just String literals or series of numbers. Try using the CTOD function (Characters to Date) and see if that resolves the problem. The Execute line should look like:
conn.Execute ("INSERT INTO amex_dist (Statement,Account,Card_user,Date,Desc,Amount) VALUES ('" & vStatement & "','" & vAccount & "','" & vCardUser & "',CTOD('" & vDate & "'),'" & vDesc & "'," & vAmount & ")")
I have a form with textboxes. I am inserting what the user enters into the textbox into a table. If the user enters an apostrophe in the textbox labeled "Me.ProjectName", I get an error. My code is:
CurrentDb.Execute "INSERT INTO Table1(ProjectNumber, Title) " & _
" VALUES('" & ProjectNumber & "','" & Me.ProjectName & "')"
You should not construct and execute dynamic SQL based on user input. You should use a parameterized query, something like:
Dim cdb As DAO.Database
Set cdb = CurrentDb
Dim qdf As DAO.QueryDef
Set qdf = cdb.CreateQueryDef("", _
"INSERT INTO Table1 (ProjectNumber, Title) VALUES (#prjnum, #title)")
qdf.Parameters("#prjnum").Value = ProjectNumber
qdf.Parameters("#title").Value = me.ProjectName
qdf.Execute
You should escape your strings possibly containing quotes by replacing a quote with 2 quotes:
Dim SQL As String
SQL = "INSERT INTO Table1(ProjectNumber, Title) " & _
" VALUES('" & ProjectNumber & "','" & Replace(Me.ProjectName, "'", "''") & "')"
CurrentDb.Execute SQL
Here is what I have, I'm trying to take fields from an Access form (data comes from one linked sql table) and insert them into another linked sql table:
StrSQL = "INSERT INTO [dbo_Expense_Projection] ([StatusID],[TravellerUFID],[Email]) " & _
VALUES(" & Me.StatusID & ", " Me.TravellerUFID & ", " Me.SubmitterUFID & ", " Me.email & ")
DoCmd.RunSQL StrSQL
But I am getting this error
Compile error: Sub or Function not defined
I think you are just missing some double quotes:
StrSQL = "INSERT INTO [dbo_Expense_Projection] ([StatusID],[TravellerUFID],[Email]) " & _
"VALUES(" & Me.StatusID & ", " Me.TravellerUFID & ", " Me.SubmitterUFID & ", """ & Me.email & """)"
DoCmd.RunSQL StrSQL
You can try to print the contents of StrSQL and check the query before running it:
Debug.Print StrSQL
but I prefer not to create SQL strings with concatenated values (what happens if Me.StravellerUFID contains a double quote?)
I would suggest you to insert data using DAO:
Dim rs as Recordset
Set rs = CurrentDb.OpenRecordset("dbo_Expense_Projection")
rs.AddNew
rs!StatusID = Me.StatusID
rs!TravellerUFID = Me.TravellerUFID
' ...other fields
rs.Update
rs.Close
There are also some ampersands missing in the SQL-String:
StrSQL = "INSERT INTO [dbo_Expense_Projection] ([StatusID],[TravellerUFID],[Email]) " & _
"VALUES(" & Me!StatusID & ", " & Me!TravellerUFID & ", " & Me!SubmitterUFID & ", """ & Me!email & """)"
And I think you should use exclamation mark between "Me" and fieldname. But I do not want to argue with the experts here about that... ;)
Here is what ended up working:
Dim StrSQL As String
StrSQL = "INSERT INTO dbo_Expense_Projection (StatusID,TravellerUFID,Email)
VALUES('" & Form!StatusID & "','" & Form!TravellerUFID & "','" & Form!Email & "')"
DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True
I am working on a database for my work and i'm trying to insert and update values from tables with sql inside the vb editor
This is my code:
Option Compare Database
Private Sub Übernehmen_Click()
Dim strSQL1 As String
Dim strSQL2 As String
Dim strSQL3 As String
Dim ArtikelNr As Integer
Dim Stück As Integer
Dim Lieferant As String
Dim Bestellnr As Integer
Dim EkPreis As String
Dim Mwst As String
Dim Einkaufsort As String
Dim GhIndex As String
Dim Datum As String
Dim Uhrzeit As String
Dim Lager As String
Dim Beschreibung As String
ArtikelNr = [Forms]![Einkauf]![ArtikelNr].Value
Stück = [Forms]![Einkauf]![Stück].Value
Lieferant = [Forms]![Einkauf]![Lieferant].Value
Bestellnr = [Forms]![Einkauf]![Bestellnr].Value
EkPreis = [Forms]![Einkauf]![EK-Preis].Value
Mwst = [Forms]![Einkauf]![Mwst-Satz].Value
Einkaufsort = [Forms]![Einkauf]![Einkaufsort].Value
GhIndex = [Forms]![Einkauf]![GH-Index].Value
Datum = [Forms]![Einkauf]![Datum].Value
Uhrzeit = [Forms]![Einkauf]![Uhrzeit].Value
Lager = [Forms]![Einkauf]![Lager].Value
strSQL1 = "INSERT INTO Einkäufe (ArtikelNr, Stück, Lieferant, Bestellnr, EKPreis, MwstSatz, Einkaufsort, GHIndex) VALUES (" & ArtikelNr & "," & Stück & ",'" & Lieferant & "','" & Bestellnr & "','" & EkPreis & "','" & Mwst & "','" & Einkaufsort & "','" & GhIndex & "');"
Beschreibung = DLast("EinkaufID", "Einkäufe")
strSQL2 = "INSERT INTO Transaktionen VALUES ('" & ArtikelNr & "','" & Datum & "','" & Lager & "','" & Stück & "','EinkaufID ' + '" & Beschreibung & "' ,'Einkauf',NULL,NULL,'" & Uhrzeit & "');"
strSQL3 = "UPDATE Lagerbestand SET Stück = Stück+" & Stück & " WHERE ArtikelNr = '" & ArtikelNr & "' AND Lager = '" & Lager & "';"
DoCmd.RunSQL strSQL1
DoCmd.RunSQL strSQL2
DoCmd.RunSQL strSQL3
End Sub
After trying to press the button it first adds the two entries and stops at the third one just to throw an error saying "Runtime Error: 3464".
After I press debug it marks the line DoCmd.RunSQL strSQL3.
I would appreciate any answer I get.
Many thanks in advance.
A quick google of "Runtime Error 3464" suggests this is a data type mismatch. You'll typically see this when you try to save a date value in a string field or something like that.
Double check the types passed to your SQL statements match the columns they should be saved to - and apply any necessary conversions if you spot differences.
Also one final heads up...by building your SQL string dynamically you are leaving yourself vulnerable to SQL Injection attacks - you should consider using ADOCommands with parameters.
My error was trying to compare an integer with a string. Even though sql does cast it from an integer to a string if you make a new entry, it does not cast it if you want to compare in a where.
sql = "insert into tbl_nurse(nurseid,nursename,deptname,dob,doj,qualification,salary)"
sql = sql & "values('" & txtNurseid.Text & "','" & TxtNursename.Text & "','" & Cmbdept.Text & "',convert(date,'" & DateTimePicker1.Value & "',103),convert(date,'" & DateTimePicker2.Value & "',103),'" & Txtqualification.Text & "','" & txtsalary.Text & "')"
conn.Execute(sql)
You should use sql-parameters to avoid sql-injection and to prevent from conversion issues like this.
Example presuming SQL-Server:
Const sql = "INSERT INTO tbl_nurse(nurseid,nursename,deptname,dob,doj,qualification,salary)" & vbCrLf & _
"VALUES(#nurseid, #nursename, #deptname, #dob, #doj, #qualification, #salary)"
Using con = New SqlConnection("Insert Your Connection String Here")
Using cmd = New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("#nurseid", txtNurseid.Text)
cmd.Parameters.AddWithValue("#nursename", TxtNursename.Text)
cmd.Parameters.AddWithValue("#deptname", Cmbdept.Text)
' -- No conversion problems anymore because you pass a DateTime -- '
cmd.Parameters.AddWithValue("#dob", DateTimePicker1.Value)
' ... other parameters ... '
con.Open()
Dim affectedRecords As Int32 = cmd.ExecuteNonQuery()
End Using
End Using
Try to change like this ..
sql = "insert into tbl_nurse(nurseid,nursename,deptname,dob,doj,qualification,salary)"
sql = sql & " values('" & txtNurseid.Text & "','" & TxtNursename.Text & "','" & Cmbdept.Text & "',#" & format(DateTimePicker1.Value.Date) & "#,#" & format(DateTimePicker2.Value.Date) & "#,'" & Txtqualification.Text & "','" & txtsalary.Text & "')"
conn.Execute(sql)
As Tim Scmelter said .. you better use parameterize input
Add Parameters as below and it works like charm
cmnd.Parameters.Add("#date_time", SqlDbType.DateTime).Value = datetime.Date;
The original post is here:
https://www.codeproject.com/Answers/552202/Conversionplusfailedpluswhenplusconvertingplusdate#answer3