Syntax error when executing INSERT INTO statement - sql

I input the Right dataSource but it didnt i cant fixed the problem cmd.ExecuteNonQuery()
saying:
Syntax error in INSERT INTO statement.
Code:
Private Sub btnadd1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnadd1.Click
Dim cmd As New OleDb.OleDbCommand
Dim Printlist1 As New DataTable
If Not con.State = ConnectionState.Open Then
con.ConnectionString = "Provider=Microsoft.Ace.OLEDB.12.0; Data Source=c:Database11.accdb"
con.Open()
cmd.Connection = con
End If
If Me.text1.Tag & "" = "" Then
cmd.CommandText = "INSERT INTO Printlist1(StickerCode, Description, Company, Department, Location, User, SerialNumber, DatePurchased, Tagable, Quantity, Brand, Model)" & _
" VALUES(" & Me.text1.Text & ",'" & Me.text2.Text & "','" & _
Me.text3.Text & "','" & Me.text4.Text & "','" & Me.text5.Text & "','" & _
Me.text6.Text & "','" & Me.text7.Text & "','" & Me.text8.Text & "','" & _
Me.text9.Text & "','" & Me.text10.Text & "','" & Me.text11.Text & "','" & _
Me.text12.Text & "')"
cmd = New OleDbCommand(cmd.CommandText, con)
cmd.ExecuteNonQuery()
Else
cmd.CommandText = "UPDATE Printlist1 " & _
" SET StickerCode='" & Me.text1.Text & _
", Description='" & Me.text2.Text & "'" & _
", Company='" & Me.text3.Text & "'" & _
", Department='" & Me.text4.Text & "'" & _
", Location='" & Me.text5.Text & "'" & _
", User='" & Me.text6.Text & "'" & _
", SerialNumber='" & Me.text7.Text & "'" & _
", DatePurchased='" & Me.text8.Text & "'" & _
", Tagable='" & Me.text9.Text & "'" & _
", Quantity='" & Me.text10.Text & "'" & _
", Brand='" & Me.text11.Text & "'" & _
", Model='" & Me.text12.Text & "'" & _
" WHERE text1=" & Me.text1.Tag
cmd.ExecuteNonQuery()
End If
RefreshData()
Me.btnclear1.PerformClick()
con.Close()
End Sub

Use a parameterized query, like this:
cmd.CommandText = "INSERT INTO Printlist1(StickerCode, Description, Company, Department, Location, User, SerialNumber, DatePurchased, Tagable, Quantity, Brand, Model)" & _
" VALUES(#StickerCode, #Description, #Company, #Department, #Location, #User, #SerialNumber, #DatePurchased, #Tagable, #Quantity, #Brand, #Model)"
cmd.Parameters.AddWithValue("#StickerCode", Me.Text1.Text)
cmd.Parameters.AddWithValue("#Description", Me.Text2.Text)
cmd.Parameters.AddWithValue("#Company", Me.Text3.Text)
cmd.Parameters.AddWithValue("#Department", Me.Text4.Text)
cmd.Parameters.AddWithValue("#Location", Me.Text5.Text)
cmd.Parameters.AddWithValue("#User", Me.Text6.Text)
cmd.Parameters.AddWithValue("#SerialNumber", Me.Text7.Text)
cmd.Parameters.AddWithValue("#DatePurchased", Me.Text8.Text)
cmd.Parameters.AddWithValue("#Tagable", Me.Text9.Text)
cmd.Parameters.AddWithValue("#Quantity", Me.Text10.Text)
cmd.Parameters.AddWithValue("#Brand", Me.Text11.Text)
cmd.Parameters.AddWithValue("#Model", Me.Text12.Text)
Note: It is best to keep the order of the parameters in line with the query, as databases like Microsoft Access will not execute the query correctly if the order is altered.

It is likely that one of your Me.textN.Text values has an apostrophe in it or some other unexpected character that is breaking your SQL quotes. The solution to this is to use parametized queries and/or stored procedure instead.
This incidentally, will also protect you form the SQL Injection attacks that take advantage of the same shortcoming in composing SQL commands as strings in the client application.
(NOTE: I am assuming the Me.text1.Text as the StickerCode is a number. Otherwise that's the problem as you are not quoting it the way you do with the other columns.)

First line is missing as '
...
"SET StickerCode='" & Me.text1.Text & "'" & _
...

You are missing single quotes around your first value. Try
" VALUES('" & Me.text1.Text & "','" & Me.text2.Text & "','" & _
Me.text3.Text & "','" & Me.text4.Text & "','" & Me.text5.Text & "','" & _
Me.text6.Text & "','" & Me.text7.Text & "','" & Me.text8.Text & "','" & _
Me.text9.Text & "','" & Me.text10.Text & "','" & Me.text11.Text & "','" & _
Me.text12.Text & "')"

Related

Access 2016 Error 3464 while coding for Update button

In access 2016 I'm trying to use an update command.I'm creating a database as my internship project as I'm unfamiliar with the coding I have been struggling a lot. I'm referring to a video by Setha Iech: https://www.youtube.com/watch?v=Ri2Y9-16AEo. When I'm using the below code an error continuously pops up
Error 3464
Private Sub cmdAdd_Click()
'when we click on button Add there are two options
'1. for insert
'2. for update
If Me.txtID.Tag & "" = "" Then
'this is for insert new
'add data to table
CurrentDb.Execute "INSERT INTO Business(ID, Project_ID, [Date_of_Enquiry], Division, Client, Description, Probability_to_win,Status, [Proposal_Submission_date], [Expected_award_date], Remarks)" & _
"VALUES ('" & Me.txtID & "','" & Me.txtProject_ID & "','" & Me.txtDate_of_Enquiry & "','" & Me.cboDivision & "','" & _
Me.txtClient & "','" & Me.txtDescription & "','" & Me.cboProbability_to_win & "','" & Me.cboStatus & "','" & Me.txtProposal_Submission_date & "','" & Me.txtExpected_award_date & "','" & Me.txtRemarks & "')"
Else
'otherwise (Tag of txtID store the ID of statement to be modified)
CurrentDb.Execute "UPDATE Business" & _
" SET ID=" & Me.txtID & _
", Project_ID='" & Me.txtProject_ID & "'" & _
", Date_of_Enquiry='" & Me.txtDate_of_Enquiry & "'" & _
", Division='" & Me.cboDivision & "'" & _
", Client='" & Me.txtClient & "'" & _
", Description='" & Me.txtDescription & "'" & _
", Probability_to_win='" & Me.cboProbability_to_win & "'" & _
", Status='" & Me.cboStatus & "'" & _
", Proposal_Submission_date='" & Me.txtProposal_Submission_date & "'" & _
", Expected_award_date='" & Me.txtExpected_award_date & "'" & _
", Remarks='" & Me.txtRemarks & "'" & _
" WHERE ID=" & Me.txtID.Tag
End If
'clear form
cmdClear_Click
'refresh data in list on form
databasesub.Form.Requery
End Sub
Thank you for your answers in advance

Edit/Update datagridview VB form

When I try to edit and update the data in datagriview it comes up with an error message saying Operator '&' is not defined for type 'TextBox' and string "".
please help. Thanks
Here is my code
Private Sub btnaddrecord_Click(sender As Object, e As EventArgs) Handles btnaddrecord.Click
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
If Me.IdentificationNotest.Tag & "" = "" Then
cmd.CommandText = "INSERT INTO vehicledefects(Codenumber, vehiclereg, datereported, defects1, repaired1, defects2, repaired2, defects3, repaired3, datefixed) " & _
" VALUES(" & Me.IdentificationNotest.Text & ",'" & Me.vehiclereg.Text & "','" & Me.datereported.Text & "','" & Me.defects1.Text & "','" & Me.repaired1.Text & "','" & _
Me.defects2.Text & "','" & Me.repaired2.Text & "','" & _
Me.defects3.Text & "','" & Me.repaired3.Text & "','" & _
Me.datefixed.Text & "')"
cmd.ExecuteNonQuery()
Else
cmd.CommandText = "UPDATE vehicledefects" & _
" SET Codenumber =" & Me.IdentificationNotest.Text & _
", vehiclereg ='" & Me.vehiclereg.Text & "'" & _
", datereported ='" & Me.datereported.Text & "'" & _
", defects1 ='" & Me.defects1.Text & "'" & _
", repaired1 ='" & Me.repaired1.Text & "'" & _
", defects2 ='" & Me.defects2.Text & "'" & _
", repaired2='" & Me.repaired2.Text & "'" & _
", defects3='" & Me.defects3.Text & "'" & _
", repaired3='" & Me.repaired3.Text & "'" & _
", datefixed='" & Me.datefixed.Text & "'" & _
" WHERE Codenumber =" & Me.IdentificationNotest.Tag
cmd.ExecuteNonQuery()
End If
refreshdata()
Me.btnclear.PerformClick()
cnn.Close()
datefixed.Text = ""
IdentificationNotest.Text = ""
End Sub
In the future, you should also post the line number the error is being thrown on.
The error is telling you that you're doing something like:
dim myString as String = myTextBox & " some more text"
in this case, you would need to do:
dim myString as String = myTextBox.Text & " some more text"
In the code you posted, I wasn't able to find an instance of this - so perhaps its somewhere else in the code. Though, the code was hard to read so I may have missed it.
You may also be aware that this code is susceptible to SQL Injection attacks

insert statement error vb.net

following is the code which is use to enter datagridview items into the table.
Dim X As DataGridViewRow
grnno = 123123
glocation = txtlocation.Text
gsupplier = txtsupplier.Text
greceivedby = txtreceivedby.Text
greceiveddate = txtreceiveddate.Text
grn_status = cmbstatus.SelectedItem
ggrossamt = txtgrossamt.Text
gdiscountamount = txtdiscount.Text
gtotalnetamount = txttotalnet.Text
sqlstr = "INSERT INTO POS_GRN_HDR(loc_code,supplier_code,created_by,created_Date,grn_status,gross_amt,disc_Amt,net_Amt) values('" & glocation & "','" & gsupplier & "','" & greceivedby & "','" & greceiveddate & "','" & grn_status & "'," & ggrossamt & "," & gdiscountamount & "," & gtotalnetamount & " )"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.ExecuteNonQuery()
For Each X In datagridItems.Rows
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) VALUES('" & grnno & "','" & X.Cells(0).Value & "','" & X.Cells(1).Value & "','" & X.Cells(2).Value & "','" & X.Cells(3).Value & "','" & X.Cells(4).Value & "','" & X.Cells(5).Value & "','" & X.Cells(6).Value & "','" & X.Cells(7).Value & "' ,'" & X.Cells(8).Value & "','" & X.Cells(9).Value & "','" & X.Cells(10).Value & "')"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.ExecuteNonQuery()
Next
the error is in the 2nd insert statement, it gives error cannot convert string to integer.. the cells from x.cell(6) are of integer type and in database also its integer type, now I want to ask should I enclose it in single quotations or not, as enclosing in single quotations give such errors like syntax '' and in double quotations it gives like cannot convert string to int type.please tell where I am doing wrong.
First of all use parametrized queries! It is safer and also more readable. You are passing some value as string but should be integer.
sqlstr = "INSERT INTO POS_GRN_HDR(loc_code,supplier_code,created_by,created_Date,grn_status,gross_amt,disc_Amt,net_Amt) _
values(#glocation, #gsupplier, #greceivedby, #greceiveddate, #grn_status, #ggrossamt, #gdiscountamount, #gtotalnetamount)"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.Parameters.AddWithValue("#glocation", glocation)
sqlcmd.Parameters.AddWithValue("#gsupplier", gsupplier) //and so on
For Each X In datagridItems.Rows
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) _
VALUES(#grnno, #item_code, #description, ...)"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.Parameters.AddWithValue("#grnno", grnno)
sqlcmd.Parameters.AddWithValue("#item_code", CType(X.Cells(0).Value, Integer)) //cast to proper type
sqlcmd.ExecuteNonQuery()
Next
Remove the single quote marks ''
For example (and referring only to x.cell(6) as per your post) use " & X.Cells(6).Value & "
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) VALUES('" & grnno & "','" & X.Cells(0).Value & "','" & X.Cells(1).Value & "','" & X.Cells(2).Value & "','" & X.Cells(3).Value & "','" & X.Cells(4).Value & "','" & X.Cells(5).Value & "', " & X.Cells(6).Value & ",'" & X.Cells(7).Value & "' ,'" & X.Cells(8).Value & "','" & X.Cells(9).Value & "','" & X.Cells(10).Value & "')"
You may also need to cast it (assuming it's always going to have a numeric value)
" & CInt(X.Cells(6).Value) &"
I will assume you know of SQL injection and this method of updating a database is generally 'outdated' and 'bad practice' now and you should use parameters instead...
Updated
Since there is a possibility of a null (and you want it to be a 0 where this is the case), you could use something like (not tested as I'm not a VB person)
dim cellSix as integer
if IsNothing(X.Cells(6).Value then
cellSix = 0
else
cellSix = CInt(X.Cells(6).Value)
end if
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) VALUES('" & grnno & "','" & X.Cells(0).Value & "','" & X.Cells(1).Value & "','" & X.Cells(2).Value & "','" & X.Cells(3).Value & "','" & X.Cells(4).Value & "','" & X.Cells(5).Value & "', " & cellSix & ",'" & X.Cells(7).Value & "' ,'" & X.Cells(8).Value & "','" & X.Cells(9).Value & "','" & X.Cells(10).Value & "')"
Or, to keep the code shorter you could use the IIF
cellSix = IIf(isnothing(CInt(X.Cells(6).Value)), 0, CInt(X.Cells(6).Value))

Microsoft Access 2010 VB InsertInto syntax error

I am totally new to Microsoft Access and VB, what i am trying to do is i have a form with unbounded textboxes which i would like upon clicking a button save the text in each textbox in its unique field.
I managed to write this piece of code with some help from online resources but it keeps giving me syntax error, if someone could point me into the correct way.
CurrentDb.Execute "INSERT INTO UserInformation(" & _
"FirstName, LastName, Company, JobTtile, PhoneNumber, Mobile, Email, Fax, " & _
"IT-DEC-MAKER-FNAME, IT-DEC-MAKER-LNAME) " & _
"VALUES('" & Me.qfirstname & "','" & Me.qlastname & "','" & Me.qcompany & "','" & _
Me.qjob & "','" & Me.qphone & "','" & Me.qmobile & "','" & Me.qemail & "','" & _
Me.qfax & "','" & Me.qitfirstname & "','" & Me.qitlastname & "');"
Since are IT-DEC-MAKER-FNAME and IT-DEC-MAKER-LNAME are invalid identifiers in SQL, you must enclose them in brackets ([ ])
CurrentDb.Execute "INSERT INTO UserInformation(" & _
"FirstName, LastName, Company, JobTtile, PhoneNumber, Mobile, Email, Fax, " & _
"[IT-DEC-MAKER-FNAME], [IT-DEC-MAKER-LNAME]) " & _
"VALUES('" & Me.qfirstname & "','" & Me.qlastname & "','" & Me.qcompany & "','" & _
Me.qjob & "','" & Me.qphone & "','" & Me.qmobile & "','" & Me.qemail & "','" & _
Me.qfax & "','" & Me.qitfirstname & "','" & Me.qitlastname & "');"
UPDATE:
I have two nice helper functions for this kind of things.
This one replaces placeholders in a string with values
Function Build(ByVal s As String, ParamArray args()) As String
' Build("LastName = {0}, FirstName = {1}","Dow","John") --> "LastName = Dow, FirstName = John".
' "\n" will be converted to vbCrLf.
Dim i As Long
s = Replace(s, "\n", vbCrLf)
For i = 0 To UBound(args)
s = Replace(s, "{" & i & "}", Nz(args(i)))
Next i
Build = s
End Function
This one converts a variant value supposed to contain a text in to a SQL value
Public Function SqlStr(ByVal v As Variant) As String
' NULL Returns: NULL
' "" Returns: NULL
' "abc" Returns: 'abc'
' "x'y" Returns: 'x''y'
Dim s As String
s = Nz(v)
If s = "" Then
SqlStr = "NULL"
Else
SqlStr = "'" & Replace(s, "'", "''") & "'"
End If
End Function
You can then use them like this making your code safer and easier to understand.
Dim template As String, sql As String
template = "INSERT INTO UserInformation(" & _
"FirstName, LastName, Company, JobTtile, PhoneNumber, Mobile, Email, Fax, " & _
"[IT-DEC-MAKER-FNAME], [IT-DEC-MAKER-LNAME]) " & _
"VALUES({0},{1},{2},{3},{4},{5},{6},{7},{8},{9});"
sql = Build(template, _
SqlStr(Me.qfirstname), SqlStr(Me.qlastname), _
SqlStr(Me.qjob), SqlStr(Me.qphone), _
SqlStr(Me.qmobile), SqlStr(Me.qemail), _
SqlStr(Me.qfax), SqlStr(Me.qitfirstname), _
SqlStr(Me.qitlastname))
CurrentDb.Execute sql
I suggest you lay out your code like so:
sSQL = "INSERT INTO UserInformation(" _
& "FirstName, LastName, Company, JobTtile, " _
& "PhoneNumber, Mobile, Email, Fax, " _
& "IT-DEC-MAKER-FNAME, IT-DEC-MAKER-LNAME) " _
& "VALUES('" _
& Me.qfirstname & "','" & Me.qlastname & "','" & Me.qcompany & "','" & Me.qjob _
& "','" & Me.qphone & "','" & Me.qmobile & "','" & Me.qemail & "','" & Me.qfax _
& "','" & Me.qitfirstname & "','" & Me.qitlastname & "');"
CurrentDB.Execute sSQL, dbFailOnError
It makes it much easier to see mistakes and the sSQL string can be printed to the immediate window for debugging. You will see you have JobTtile.
It is usually better to use an instance of CurrentDB:
Dim db As DAO.Database
Set db = CurrentDB
I wonder why you do not just bind a recordset?

app.config connection string does not work

this piece of code works fine....
Private Sub save()
Dim con As New SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Chuttu VB\Projects\LIC\LIC.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")
Dim sql As New SqlClient.SqlCommand("INSERT INTO ProposerDetails " & _
"VALUES (" & Convert.ToInt32(PolicyNumberTextBox.Text) & ",'" & NameTextBox.Text & "','" & AgeTextBox.Text & "','" & PhoneTextBox.Text & "','" & AddressTextBox.Text & "','" _
& NomineeTextBox.Text & "','" & NomineeRelationTextBox.Text & "'," & PlanID() & ",'" & PolicyTermTextBox.Text & "','" & PremiumAmountTextBox.Text & "','" _
& PremiumTypeComboBox.Text & "','" & SumProposedTextBox.Text & "','Date' )", con)
MsgBox(sql.CommandText)
con.Open()
MsgBox(con.State.ToString)
Dim i As Integer = sql.ExecuteNonQuery
MsgBox(i.ToString)
con.Close()
sql.Dispose()
con.Dispose()
ToolStripStatusLabelMessage.Text = "Saved"
End Sub
as soon as i change the connection string to the connection string from app.config it stops working(adding data to DB)
Private Sub save()
Dim con As New SqlClient.SqlConnection(LIC.My.Settings.LICConnectionString)
Dim sql As New SqlClient.SqlCommand("INSERT INTO ProposerDetails " & _
"VALUES (" & Convert.ToInt32(PolicyNumberTextBox.Text) & ",'" & NameTextBox.Text & "','" & AgeTextBox.Text & "','" & PhoneTextBox.Text & "','" & AddressTextBox.Text & "','" _
& NomineeTextBox.Text & "','" & NomineeRelationTextBox.Text & "'," & PlanID() & ",'" & PolicyTermTextBox.Text & "','" & PremiumAmountTextBox.Text & "','" _
& PremiumTypeComboBox.Text & "','" & SumProposedTextBox.Text & "','Date' )", con)
MsgBox(sql.CommandText)
con.Open()
MsgBox(con.State.ToString)
Dim i As Integer = sql.ExecuteNonQuery
MsgBox(i.ToString)
con.Close()
sql.Dispose()
con.Dispose()
ToolStripStatusLabelMessage.Text = "Saved"
End Sub
NOTE: I get no errors.
Here is a short deal explanation.
This is how you use a connection string from the config file.
Dim sqlConn as SqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings("myConnectionString").ConnectionString)
Here is a link to how to do a parameterized queries
Try changing LIC.My.Settings.LICConnectionString
to ConfigurationManager.ConnectionStrings["LICConnectionString"].ConnectionString