I am using OLEDB to connect to a Microsoft Access Database. I want to insert "ItemDesc" field data in "tblCallibrationNewGauge" from "tblItemMst" and another field such as "ItemCode","Customer","Quantity" values taken from users. Below is my code:
If con.State = ConnectionState.Open Then
con.Close()
con.Open()
Else
con.Open()
End If
Dim cmd As New OleDbCommand("Insert Into tblCallibrationNewGauge(ItemCode,ItemDesc,Customer,Quantity)VALUES('" + partCode.Text.ToString() + "',(Select ItemDesc from tblItemMst where ItemCode='" + partCode.Text.ToString() + "'),'" + cmb_customer.Text.ToString() + "','" + quantity.Text.ToString() + "'",con)
If cmd.ExecuteNonQuery() Then
MessageBox.Show("Data Inserted")
End If
con.Close()
I'm getting exception error for this.
Is it possible to do so? or
Is there any way to insert data into table where some fields are taken from other table and some fields taken from winform Control?
Thanks in Advance.
change command text like this:
Dim cmd As New OleDbCommand("Insert Into tblCallibrationNewGauge( ItemCode,ItemDesc,Customer,Quantity) SELECT '" + partCode.Text.ToString() + "', ItemDesc,'" + cmb_customer.Text.ToString() + "','" + quantity.Text.ToString() + "' from tblItemMst where ItemCode='" + partCode.Text.ToString() + "'",con)
This question already has an answer here:
VB 2010 INSERT INTO syntax error
(1 answer)
Closed 6 years ago.
I have a program in VB.NET that will input data from textboxes into an Access database. Here is sample image:
This is the code I am using and it gives me an error:
m = TextBox1.Text
b = "'" + TextBox2.Text + "'"
x = "'" + TextBox3.Text + "'"
d = TextBox4.Text
n = "'" + TextBox5.Text + "'"
Dim s2 As String
s2 = "insert into users1 ( num , name1 , pass , add , phone ) " & " values ( " + m + " , " + n + " , " + b + " , " + x + " , " + d + " ) "
Dim cmd2 As New OleDbCommand(s2, con)
cmd2.ExecuteNonQuery()
The reason your SQL is failing is that "add" is a reserved word. i.e. you cannot use it without putting it in square brackets - [add]. As above you should parameterise your query, so one of these will work...
Using oleCmd As New OleDbCommand("Insert Into users1 (num,name1,pass,[add],phone) values (#num,#name1,#pass,#add,#phone)", con)
oleCmd.Parameters.Add("#num", OleDbType.Integer).Value = Textbox1.Text
oleCmd.Parameters.Add("#name1", OleDbType.VarChar).Value = Textbox2.Text
oleCmd.Parameters.Add("#pass", OleDbType.VarChar).Value = Textbox3.Text
oleCmd.Parameters.Add("#address", OleDbType.VarChar).Value = Textbox4.Text
oleCmd.Parameters.Add("#phone", OleDbType.Integer).Value = Textbox5.Text
oleCmd.ExecuteNonQuery()
End Using
Using oleCmd As New OleDbCommand("Insert Into users1 (num,name1,pass,[add],phone) Values (?,?,?,?,?)", con)
oleCmd.Parameters.AddWithValue("?", Textbox1.Text)
oleCmd.Parameters.AddWithValue("?", Textbox2.Text)
oleCmd.Parameters.AddWithValue("?", Textbox3.Text)
oleCmd.Parameters.AddWithValue("?", Textbox4.Text)
oleCmd.Parameters.AddWithValue("?", Textbox5.Text)
oleCmd.ExecuteNonQuery()
End Using
Note, it will fail if the data types do not match what you are trying to insert, so if you try to insert text in num or phone it will fail. You will need to validate your input and preferably convert them rather than use the textbox Text.
Error in my vb but correct in my sql query. Can somebody can correct my VB code.
This is my wrong code in VB
cmd = New Odbc.OdbcCommand("SELECT * FROM tblvendorpartnumber WHERE vendorpnumber ='" & Trim(TextBox11.Text.TrimEnd()) & " OR vendorpnumber ='" & Trim(TextBox2.Text.TrimEnd()) & "'", con)
This is my correct code in mysql query
SELECT *
FROM pcba_info.tblvendorpartnumber
WHERE partnumber = '' or vendorpnumber = '';
You must resolved the problem in SQL injections to
You forgot to include the pair of other single quote.
From
TextBox11.Text.TrimEnd()) & " OR
To
Trim(TextBox11.Text.TrimEnd()) & "' OR
To form as
cmd = New Odbc.OdbcCommand("SELECT * FROM tblvendorpartnumber WHERE vendorpnumber ='" & TextBox11.Text.Trim().Replace("'", "''") & "' OR vendorpnumber ='" & TextBox2.Text.Trim().Replace("'", "''") & "'", con)
You need to avoid mixing the VB string functions with those of SQL. Write the entire query inside quotes to be certain will work in SQL.
Try like this
Trim will trim any leading or trailing blank spaces from a string. So if the string was " Text", then Trim would delete those spaces for you, leaving just "Text".
Dim S1,S2 as String
S1 = TextBox11.Text
S2 = TextBox12.Text
cmd = New Odbc.OdbcCommand("SELECT * FROM tblvendorpartnumber WHERE vendorpnumber ='" & S1.Trim & " OR vendorpnumber ='" & S2.Trim & "'", con)
I have problem with inserting text from txt file into SQl Compact edition database.
the line in text file is like bellow:
item_code,Loc,cost_price,run_spr,recd_dt,disp_flag,R_qty,s_qty,a_qty,stk_qty,O_qty,
"017245588","I01","0.000","0.000","261013","N","0.000000","-2.000000","0.000000","-2.000000","0.000000"
it has 11 field
when I using this insert statement bellow:
Dim sqlstr As String
Dim sr As StreamReader = New StreamReader("C:\SKORPIO\pdt_item.txt")
Dim line As String = sr.ReadLine()
While Not (sr.EndOfStream)
line = sr.ReadLine()
Dim fields() As String = line.Split(",")
sqlstr = "INSERT INTO pdt_item (item_code,loc,cost_price,run_spr,recd_dt,disp_flag,R_qty,s_qty,a_qty,stk_qty,O_qty) VALUES( '" & fields(0) & "' ,'" & fields(1) & "','" & fields(2) & "','" & fields(3) & "','" & fields(4) & "','" & fields(5) & "','" & fields(6) & "','" & fields(7) & "','" & fields(8) & "','" & fields(9) & "','" & fields(10) & "' )"
Dim obj As SqlCeCommand = New SqlCeCommand(sqlstr, conn)
obj.ExecuteNonQuery()
the insert statement been like this
INSERT INTO pdt_item (item_code,loc,cost_price,run_spr,recd_dt,disp_flag,R_qty,s_qty,a_qty,stk_qty,O_qty) VALUES( '"017245588"' ,'"I01"','"0.000"','"0.000"','"261013"','"N"','"0.000000"','"-2.000000"','"0.000000"','"-2.000000"','"0.000000"' )
so because of two double quotations its give error
note that i did test manually without double quotations like in statement bellow its working normally.
INSERT INTO pdt_item (item_code,loc,cost_price,run_spr,recd_dt,disp_flag,R_qty,s_qty,a_qty,stk_qty,O_qty) VALUES( '017245588' ,'I01','0.000','0.000','261013','N','0.000000','-2.000000','0.000000','-2.000000','0.000000' )
So please how I can write code in VB to do this
The correct approach to this operations is through a parameterized query.
The matter is further complicated from the presence of double quotes around the field values that, I suppose, need to be removed before storing the value in the database
However, this could be the correct code....
Dim fields() As String = line.Split(",")
sqlstr = "INSERT INTO pdt_item " & _
"(item_code,loc,cost_price,run_spr,recd_dt,disp_flag," & _
"R_qty,s_qty,a_qty,stk_qty,O_qty) VALUES " & _
"( #p1, #p2, #o3, #p4, #p5, #p6, #p7, #p8, #p9, #p10, #p11)"
Dim obj As SqlCeCommand = New SqlCeCommand(sqlstr, conn)
obj.Parameters.AddWithValue("#p1", fields(0).Trim(""""c))
obj.Parameters.AddWithValue("#p2", fields(1).Trim(""""c))
obj.Parameters.AddWithValue("#p3", fields(2).Trim(""""c))
obj.Parameters.AddWithValue("#p4", fields(3).Trim(""""c))
obj.Parameters.AddWithValue("#p5", fields(4).Trim(""""c))
obj.Parameters.AddWithValue("#p6", fields(5).Trim(""""c))
obj.Parameters.AddWithValue("#p7", fields(6).Trim(""""c))
obj.Parameters.AddWithValue("#p8", fields(7).Trim(""""c))
obj.Parameters.AddWithValue("#p9", fields(8).Trim(""""c))
obj.Parameters.AddWithValue("#p10", fields(9).Trim(""""c))
obj.Parameters.AddWithValue("#p11", fields(10).Trim(""""c))
obj.ExecuteNonQuery()
There is still a problem related to the datatype of the columns in the datatable. This code assumes that every column is of type text and so every parameter value is passed as a string. If this is not the case a conversion (and a check if the value could be effectively converted) is needed when adding the parameter value.
EDIT Looking at your comment below it is clear that the simple split operation is not enough to handle correctly the file data. You need to use an instance of a TextFieldParser class. It has a property named: HasFieldEnclosedInQuotes that, when set to true, allows to ignore the field separator (the comma) when it appears inside the double quotes
So your loop could be replaced by: (Warning NOT TESTED)
Using sr As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\SKORPIO\pdt_item.txt")
sr.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
sr.Delimiters = New String() {","}
sr.HasFieldEnclosedInQuotes = True
Dim fields As String() = sr.ReadFields()
While Not sr.EndOfData
fields = sr.ReadFields()
......
What about removing the quotes first?
Instead of :
line.Split(",")
line.Replace( """", "" ).Split(",")
NOTE: this isn't good if you actually have any data with quotes in it that where you want quotes written to your database
Please use string as
"INSERT INTO pdt_item (item_code,loc,cost_price,run_spr,
recd_dt,disp_flag,R_qty, qty,a_qty,stk_qty,O_qty)
VALUES( '" + fields(0) + "' ,'" + fields(1) + "','" + fields(2) + "','" + fields(3) +
"','" + fields(4) + "','" + fields(5) + "','" +
fields(6) + "','" + fields(7) + "','" + fields(8) + "','" +
fields(9) + "','" + fields(10) + "' )";
My objective is to input all checked items from a checkbooxlist into a single column in my database.
I understand it is not a good design. However, this is the requirement.
Here is the code I use to get all the selected items from checkboxlist:
Dim listitems As String
listitems = ControlChars.CrLf
For i = 0 To (chkActivities.Items.Count - 1)
If chkActivities.GetItemChecked(i) = True Then
listitems = listitems & (i + 1).ToString & chkActivities.Items(i).ToString & ControlChars.CrLf
End If
Next
Here is the connection string and command executed to populate my table:
>
objCon.Open()
objCmd = New SqlCommand("insert into activity_by_customer (userID, city, personal_activities, BookingDate, price) values ( '" & frmLogin.userID & "','" & cbbCity.Text & "','" & listitems & "','" & Date.Today & "','" & lblpriceValue.Text & "' )", objCon)
objCmd.ExecuteNonQuery()
activitiesbycustomer.Update(Me.ResourcesDataSet.activity_by_customer)
MsgBox("Your booking has been successful")
objCon.Close()
However when I execute this code it crashes with an error. The error is as follows:
Incorrect syntax near 's'.
Unclosed quotation mark after the character string ' )'.
This error happens to appear because of 'listitems'.
Any help would be appreciated.
Not a problem in how you build your listitems, but in how you pass the values to the database.
Do not use string concatenation to build a sql command
objCon.Open()
objCmd = New SqlCommand("insert into activity_by_customer " & _
"(userID, city, personal_activities, BookingDate, price) " & _
"values (#usrID, #city, #itms, #dt, #price)", objCon)
objCmd.Parameters.AddWithValue("#usrID",frmLogin.userID)
objCmd.Parameters.AddWithValue("#city",cbbCity.Text)
objCmd.Parameters.AddWithValue("#itms", listitems)
objCmd.Parameters.AddWithValue("#dt",Date.Today)
objCmd.Parameters.AddWithValue("#price", lblpriceValue.Text)
objCmd.ExecuteNonQuery()
....
In this way, the framework code formats your values considering the presence of characters like a single quote and avoiding the consequent syntax error. Moreover, in this way you avoid Sql Injection attacks