insert statement error vb.net - sql

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

Related

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)

Syntax error when executing INSERT INTO statement

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 & "')"

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

How to break long string to multiple lines

I'm using this insert statement in my code in vba excel but i'm not able to break it into more than one line
SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & " _
,'" & txtContractStartDate.Value & "' _
,'" & txtSeatNo.Value & "' _
,'" & txtFloor.Value & "','" & txtLeaves.Value & "')"
It is giving error "Expected end of statement". Plz help.
You cannot use the VB line-continuation character inside of a string.
SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & _
"','" & txtContractStartDate.Value & _
"','" & txtSeatNo.Value & _
"','" & txtFloor.Value & "','" & txtLeaves.Value & "')"
you may simply create your string in multiple steps, a bit redundant but it keeps the code readable and maintain sanity while debugging or editing
SqlQueryString = "Insert into Employee values("
SqlQueryString = SqlQueryString & txtEmployeeNo.Value & " ,"
SqlQueryString = SqlQueryString & " '" & txtEmployeeNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtContractStartDate.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtSeatNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtContractStartDate.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtSeatNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtFloor.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtLeaves.Value & "' )"
If the long string to multiple lines confuses you. Then you may install mz-tools addin which is a freeware and has the utility which splits the line for you.
Download Mz-tools
If your string looks like below
SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & "','" & txtContractStartDate.Value & "','" & txtSeatNo.Value & "','" & txtFloor.Value & "','" & txtLeaves.Value & "')"
Simply select the string > right click on VBA IDE > Select MZ-tools > Split Lines

OleDbException was Unhandled: Syntax error in INSERT INTO statement

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 "'".