OleDbException was Unhandled: Syntax error in INSERT INTO statement - vb.net

con.Open()
cmd.CommandText = "Insert Into tblEmp (FN,MN,LN,PAddHN,PAddSB,PAddMun,VPA,BD,BP,Tel,Rel,Cit,Height,Weight,Gend,SN,SOcc,NoC,AgeC,Stat,DS,FaN,FaOcc,MaN,MaOcc,PAdd,PTCN,PTCP,SSS,TIN,PHILH,PAGIBIG,CPNo,Sued,Age,BankAcc,empRfID,Principal,Department,Position,DRate,empID,OffT) Values('" & zfn & "','" & zmn & "','" & zln & "','" & zpaddhn & "','" & zpaddsb & "','" & zpaddmun & "','" & zvpa & "','" & zbd & "','" & zbp & "','" & ztel & "','" & zrel & "','" & zcit & "','" & zheight & "','" & zweight & "','" & zgend & "','" & zsn & "','" & zsocc & "','" & znoc & "','" & zagec & "','" & zstat & "','" & zds & "','" & zfan & "','" & zfaocc & "','" & zman & "','" & zmaocc & "','" & zpadd & "','" & zptcn & "','" & zptcp & "','" & zsss & "','" & ztin & "','" & zphilh & "','" & zpagibig & "','" & zcpno & "','" & zsued & "','" & zage & "','" & txtBankAcc.Text & "','" & zempRefID & "','" & cmbPrin.SelectedItem & "','" & cmbDept.SelectedItem & "','" & txtPos.Text & "','" & txtDRate.Text & "','" & empID & "','" & zOffTime & "')"
cmd.ExecuteNonQuery()
con.Close()
I got an error when running this in my program.. but when i paste the command in my ms access query and it runs successfully. is there any problem in my code? Pls help tnx.

where is your add parameter value?
You can try this
Try
con = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Dir\DB.accdb")
Dim command As String
command = "INSERT INTO Table (NOTIF, EMP_NO, EMP_NAME, [POSITION]) VALUES (#NOTIF, #EMP_NO, #EMP_NAME, #POSITION)"
con.Open()
Dim cmd As OleDbCommand
cmd = New OleDbCommand(command, con)
cmd.Parameters.AddWithValue("#NOTIF", NOTIFTextBox.Text)
cmd.Parameters.AddWithValue("#EMP_NO", EMP_NOTextBox.Text)
cmd.Parameters.AddWithValue("#EMP_NAME", EMP_NAMETextBox.Text)
cmd.Parameters.AddWithValue("#POSITION", POSITIONTextBox.Text)
cmd.ExecuteNonQuery()
Catch exceptionObject As Exception
MessageBox.Show(exceptionObject.Message)
Finally
con.Close()
End Try
this code i have used before, it work perfectly
Also your name of the field look like contain illegal value to VB.net, so must like this
[Height],[Weight],.... You can try to check it in you DATASET > Configure > Select Statement > Insert and you will look the illegal value.
Just like my POSITION field, it was illegal, so must contain "[]"

You may not use the "'", if the datatype is something like numbers. If i interprete it correctly, some of your fields are numbers.
con.Open()
cmd.CommandText = "Insert Into tblEmp (someInt, someString) VALUES (12, 'asdf')"
cmd.ExecuteNonQuery()
con.Close()
Beside this, you should get the same error in Acces, if you run you Query again. Use the debugger and add a Breakpoint at the "cmd.ExecuteNonQuery()" to get the finished query command string with all "'".

Related

"Error converting data type varchar to numeric" when I export data from Excel to SQL Server using VBA

I have created a macro in Excel to import and export data from SQL Server. However, when I try to export data, it throws an error
[Microsoft][ODBC SQL Server Driver][SQL Server]
Error converting data type varchar to numeric
The code worked fine when I was exporting integer numbers. The error came up when I tried exporting real numbers.
Dim gil, gibnr, gul, fil, fibnr, ful, qil, qibnr, qul, xil, xibnr, xul, oil, oibnr, oul, cil, cibnr, cul, nil, nibnr, nul, bul, hul, lul, indul As Long
conn.Execute "insert into dbo.Intl_LL (UWU,OBU,Profile_ID, Insured_name, Claim_number,Claim_desc, Event_Name, UY, AY, AQ, Date_of_loss, Region, CCY, Policy_number, Branch, LE, MPL,Claim_alert_email, Comments, [Large Profile Flag], [Earmark Flag], [Tracked for Qtrly dev], [Gross Incurred], [Gross IBNR], [Gross Ultimate], [FAC Incurred], [FAC IBNR], [FAC Ultimate], [QS Incurred],[QS IBNR],[QS Ultimate],[XOL Incurred],[XOL IBNR],[XOL Ultimate],[Ceded OTH Incurred],[Ceded OTH IBNR],[Ceded OTH Ultimate],[Ceded Total Incurred],[Ceded Total IBNR],[Ceded Total Ultimate],[Net Incurred],[Net IBNR],[Net Ultimate],[Booked Ultimate],version)" & _
"values ('" & sUWU & "', '" & sOBU & "','" & sProfile & "', '" & sInsured & "','" & sClaim & "','" & sClmdesc & "','" & sEvent & "','" & sUY & "','" & sAY & "','" & sAQ & "','" & sDOL & "','" & sRegion & "','" & sCCY & "','" & sPolnum & "','" & sBranch & "','" & sLE & "','" & sMPL & "','" & sClaimalert & "','" & sComm & "','" & sLargeF & "','" & sEarF & "','" & sTrackF & "','" & gil & "', '" & gibnr & "','" & gul & "','" & fil & "','" & fibnr & "','" & ful & "','" & qil & "','" & qibnr & "','" & qul & "','" & xil & "','" & xibnr & "','" & xul & "','" & oil & "','" & oibnr & "','" & oul & "','" & cil & "','" & cibnr & "','" & cul & "','" & nil & "','" & nibnr & "','" & nul & "','" & bul & "', '" & ver & "')"
I have ensured that the variables that have Long data type in VBA are numeric(7, 11) type in SQL Server.
Feel free to ask for more information about the problem. Thanks.
MySQL must assume the values are supposed to be the same type as the "mycol" column and silently converts them. - It does the same when you try to compare an INT to a string.
However, you should try not to quote values that are supposed to be numbers. Even if MySQL does automatically convert some of them, it costs a few cycles and the behavior may not be consistent.
Bottom line: always leave numbers unquoted, and only quote strings and dates.

insert data to datagridview vb.net

how do i insert money row and colomns to datagridview?
like i went to insert to datagridview this
is my code:
Private Sub btnSimpan_Click(sender As Object, e As EventArgs) Handles btnSimpan.Click
Call konek()
Dim simpan As String
Dim hasil As Integer
simpan = ("INSERT INTO T_Penjadwalan(Kode_Penjadwalan,Kelas,Kode_Jam,Jam_Mulai,Jam_Selesai,Senin,Selasa,Rabu,Kamis,Jumat,Sabtu) VALUES ('" & TBPENJADWALAN.Text & "','" & CBKelas.Text &
"','" & KJ1.Text & "','" & KJ2.Text & "','" & KJ3.Text & "','" & KJ4.Text & "','" & KJ5.Text & "','" & KJ6.Text & "','" & KJ7.Text & "','" & KJ8.Text & "','" & KJ9.Text &
"','" & JM1.Text & "','" & JM2.Text & "','" & JM3.Text & "','" & JM4.Text & "','" & JM5.Text & "','" & JM6.Text & "','" & JM7.Text & "','" & JM8.Text & "','" & JM9.Text &
"','" & JS1.Text & "','" & JS2.Text & "','" & JS3.Text & "','" & JS4.Text & "','" & JS5.Text & "','" & JS6.Text & "','" & JS7.Text & "','" & JS8.Text & "','" & JS9.Text &
"','" & Senin1.Text & "','" & Senin2.Text & "','" & Senin3.Text & "','" & Senin4.Text & "','" & Senin5.Text & "','" & Senin6.Text & "','" & Senin7.Text &
"','" & Selasa1.Text & "','" & Selasa2.Text & "','" & Selasa3.Text & "','" & Selasa4.Text & "','" & Selasa5.Text & "','" & Selasa6.Text & "','" & Selasa7.Text &
"','" & Rabu1.Text & "','" & Rabu2.Text & "','" & Rabu3.Text & "','" & Rabu4.Text & "','" & Rabu5.Text & "','" & Rabu6.Text & "','" & Rabu7.Text &
"','" & Kamis1.Text & "','" & Kamis2.Text & "','" & Kamis3.Text & "','" & Kamis4.Text & "','" & Kamis5.Text & "','" & Kamis6.Text & "','" & Kamis7.Text &
"','" & Jumat1.Text & "','" & Jumat2.Text & "','" & Jumat3.Text & "','" & Jumat4.Text & "','" & Jumat5.Text & "','" & Jumat6.Text & "','" & Jumat7.Text &
"','" & Sabtu1.Text & "','" & Sabtu2.Text & "','" & Sabtu3.Text & "','" & Sabtu4.Text & "','" & Sabtu5.Text & "','" & Sabtu6.Text & "','" & Sabtu7.Text & "')")
Try
cmd = New SqlCommand(simpan, conn)
hasil = cmd.ExecuteNonQuery()
If hasil > 0 Then
MessageBox.Show("Data Tersimpan", "Sukses", MessageBoxButtons.OK, MessageBoxIcon.Information)
Call tampilgridpenjadwalan()
End If
Catch ex As Exception
MessageBox.Show("Failed : " & ex.Message, "Gagal", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub}
First of all, as others have said, it is better to use parameters when executing SQL queries in VB.NET. It has many benefits and it's fairly simple.
Taking a snippet of your insert query as an example, instead of defining the first value clause as '" & TBPENJADWALAN.Text & "' the first value might be #TBPENJADWALAN.
The string from TBPENJADWALAN.Text is then passed to #TBPENJADWALAN using the following code:
cmd.Parameters.Add("#TBPENJADWALAN", OleDbType.VarChar, 50).Value = TBPENJADWALAN.Text
OleDbType.VarChar = Type of data you're storing
50 = Size of your field
So instead of your code as follows...
simpan = ("INSERT INTO T_Penjadwalan(Kode_Penjadwalan) VALUES ('" & TBPENJADWALAN.Text & "')
...it would be:
simpan = ("INSERT INTO T_Penjadwalan(Kode_Penjadwalan) VALUES (#TBPENJADWALAN)")
cmd.Parameters.Add("#TBPENJADWALAN", OleDbType.VarChar, 50).Value = TBPENJADWALAN.Text
It's much cleaner and more secure. You can take that example and change the rest of your insert query.
In terms of your original question about inserting data to a DataGridView, in my experience, it's best to create a DataSet and Adapter to fill it. Try this:
Dim adapter As SQLDataAdapter
Dim ds As New DataSet
adapter = New SQLDataAdapter(simpan, cmd)
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)

incorrect syntax near 's' vb.net

I'm getting the error Incorrect syntax near 's'. Error appears after inputting data in SQL sometimes it doesn't appear but when same characters will input the error appears.
Error lined in the ExecuteNonQuery
conn = New SqlConnection(constr)
conn.Open()
comm = New SqlCommand("Insert into Admins(Firstname, Lastname, Birthday, Contact, Email, Address, Username, Password, SecurityQ1, SecurityQ2, SecurityI1, SecurityI2, SecurityA1, SecurityA2, Type) values ('" & BunifuMetroTextbox1.Text & "','" & BunifuMetroTextbox2.Text & "','" & BunifuDatepicker1.Value & "','" & BunifuMetroTextbox3.Text & "','" & BunifuMetroTextbox8.Text & "','" & BunifuMetroTextbox9.Text & "','" & BunifuMetroTextbox4.Text & "','" & BunifuMetroTextbox5.Text & "','" & BunifuDropdown1.selectedValue & "','" & BunifuDropdown2.selectedValue & "','" & BunifuDropdown1.selectedIndex & "','" & BunifuDropdown2.selectedIndex & "','" & BunifuMetroTextbox6.Text & "','" & BunifuMetroTextbox7.Text & "','" & admintype & "')", conn)
affector = comm.ExecuteNonQuery
conn.Close()

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))

Operator '&' is not defined for string "Insert into Table_Name(XYZ_" and type 'Byte()'

I get this error →
Operator '&' is not defined for string "Insert into SP_Master_Entry (SP_" and type 'Byte()'.
I think this error is caused near dr(SP_Photo) and am very much new to VB.NET
mainModule.DatabaseNonQuery("
Insert into SP_Master_Entry
(SP_ID, SP_Name, Gender, Date_Of_Birth, Date_Of_Join, Branch_ID,
SP_Area_ID, SP_Address1, SP_Address2, SP_Address3, PIN, Qualification,
Contact_Number, SP_Photo, SP_Status, Caste, SHG_Member, Marital_Status,
Salary, KYC_TYPE_ID, KYC_Code, Reference, Reference2, Agreement, Resigned,
ResignedDate,delivery_status,allow_edit)
VALUES (" & dr("SP_ID") & ",'" & dr("SP_Name") & "','" & dr("Gender") & "','"
& dr("Date_Of_Birth") & "','" & dr("Date_Of_Join") & "',"
& dr("Branch_ID") & "," & dr("SP_Area_ID") & ",'" & dr("SP_Address1")
& "','" & dr("SP_Address2") & "','" & dr("SP_Address3") & "',"
& dr("PIN") & "," & dr("Qualification") & ",'" & dr("Contact_Number")
& "'," & dr("SP_Photo") & ",'" & dr("SP_Status") & "','" & dr("Caste")
& "','" & dr("SHG_Member") & "','" & dr("Marital_Status") & "','"
& dr("Salary") & "'," & dr("KYC_TYPE_ID") & ",'" & dr("KYC_Code")
& "','" & dr("Reference") & "','" & dr("Reference2") & "','"
& dr("Agreement") & "','" & dr("Resigned") & "','" & dr("ResignedDate")
& "','" & dr("delivery_status") & "','" & dr("allow_edit") & "','"
& Today.Date.ToString & "','" & Today.Date.ToString & "')")
The error says it all: Byte() (i.e. an array of bytes) is a fundamentally different type from String and you cannot concatenate the two. How to solve this depends on what data these bytes contain and what you want to get from them. The Encoding.GetString method may help, if the bytes contain encoded text data.
More generally, the code you posted is beyond the pale. You cannot write code like this, it’s completely unreadable and hence worthless. Refactor it.
Before inserting an image.
Convert to byte array,i.e dim imgbyte as byte=datarow("Your Photo column")
Then convert/build a Memory Stream and build image for the memory stream
Now use the image which you have build and use it in insert query as shown below
Dim img_b As Byte() = dr("SP_Photo")
Dim img_stream As IO.MemoryStream
img_stream = New IO.MemoryStream(img_b)
Dim img As Image = Image.FromStream(img_stream)
Dim cmd As New SqlCommand("update user_table_name set user_Photo=#image where user_ID=" & dr("SP_ID"), connstr)
cmd.Parameters.Add("#image", SqlDbType.Image, img_b.Length).Value = img_b
cmd.ExecuteNonQuery()