How to split double quotation from string in VB.net - sql

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) + "' )";

Related

How can I insert a single quote (') in sql?

I got some strings that contains a single quote (') like Mayor's Office:
Dim Str = "Insert into EntryTbl(Office, DateCreated, TimeCreated)" & _
"Values('" & OfficeBox.Text & "', " & _
" '" & Now.ToShortDateString & "', " & _
" '" & Now.ToString("HH:mm:ss") & "')"
and the officebox.text contains a string Mayor's Office
Glad for any help :)
IMO, parametrized query is better because it prevents SQL injection and it will handle escaping for you(no need to write additional method to handle escaping)
Dim cmd As New SqlCommand("", Conn())
With cmd
.CommandText = "Insert into tbl(Office, DateCreated, TimeCreated)" & _
"Values(#office,#DateCreated,#TimeCreated)"
.Parameters.AddWithValue("#office", OfficeBox.Text)
.Parameters.AddWithValue("#DateCreated", Now.ToShortDateString)
.Parameters.AddWithValue("#TimeCreated", Now.ToString("HH:mm:ss"))
.ExecuteNonQuery()
End With
Take a look at How do I create a parameterized SQL query? Why Should I? for more informations
The built in solution is to use
QUOTENAME(#string)
function to put the quotes.

data is not inserted to database

i tried to insert the data into database with this code
Public Sub AddUser()
Dim con As dbConn = New dbConn()
Dim SqlSelect As String
SqlSelect = "SELECT * FROM login Where user_id='" & WorkerID_.Text & "'"
Dim cmd As New OleDbCommand(SqlSelect, con.oleconnection)
Dim reader As OleDbDataReader
Dim da As New OleDbDataAdapter
con.open()
reader = cmd.ExecuteReader()
reader.Read()
If reader.HasRows() Then
reader.Close()
con.close()
FailureText.Text = "User ID already exists!"
Else
reader.Close()
con.close()
Dim InsertSQL As String
InsertSQL = "INSERT INTO login (user_id, user_role, user_password, user_status) VALUES "
InsertSQL &= "('" & WorkerID_.Text & "', "
InsertSQL &= "'Worker', "
InsertSQL &= "'12345', 1)"
Dim SqlUpdate As String
SqlUpdate = "INSERT INTO Worker (ID, WorkerID, WorkerName, DoB, Address, Phone, Email, CompanyName, PassportNum, PassportExp, VisaExp, VisaStatus, user_id) VALUES (default,"
SqlUpdate &= "'" & WorkerID_.Text & "', "
SqlUpdate &= "'" & WorkerName.Text & "', "
SqlUpdate &= "'" & DoB.Text & "', "
SqlUpdate &= "'" & Address.Text & "', "
SqlUpdate &= "'" & Phone.Text & "', "
SqlUpdate &= "'" & Email.Text & "', "
SqlUpdate &= "'" & Company.SelectedValue & "', "
SqlUpdate &= "'" & PassNum.Text & "', "
SqlUpdate &= "'" & PassExp.Text & "', "
SqlUpdate &= "'" & VisaExp.Text & "', "
SqlUpdate &= "'No Visa', "
SqlUpdate &= "'" & WorkerID_.Text & "') "
Dim insertCommand As New OleDbCommand(SqlUpdate, con.oleconnection)
Dim cmd1 As New OleDbCommand(InsertSQL, con.oleconnection)
Try
con.open()
cmd1.ExecuteNonQuery()
insertCommand.ExecuteNonQuery()
Catch
FailureText.Text = "Unable to add user"
Finally
con.close()
End Try
End If
Response.Redirect("Workers.aspx")
End Sub
the Insert into login part is working. the data is well inserted. but for the insert into worker part is not working. the data is not inserted into the table. the program shows no error and it still can work. what could possibly wrong with this?
Read another answer on OleDb I just answered on another post. You will be wide open to sql-injection too. Parmaeterize queries. By you concatenating strings to build one command, what if one value has a single-quote within the text entry. You are now hosed. What if someone puts malicious SQL commands and then deletes your records or entire table(s). Learn to parameterize your queries and also clean values, especially if coming from a web interface.
Your commands should probably be updated something like
Dim con As dbConn = New dbConn()
Dim SqlSelect As String
SqlSelect = "SELECT * FROM login Where user_id= #parmUserID"
Dim cmd As New OleDbCommand(SqlSelect, con.oleconnection)
cmd.Parameters.AddWithValue( "parmUserID", WorkerID_.Text )
Follow-suit with the Insert and update commands... parameterize them but using #variable place-holders in your commands.
Dim InsertSQL As String
InsertSQL = "INSERT INTO login (user_id, user_role, user_password, user_status) "
InsertSQL &= " VALUES ( #parmUser, #parmRole, #parmPwd, #parmStatus )"
Dim cmdInsert As New OleDbCommand(InsertSQL, con.oleconnection)
cmdInsert.Parameters.AddWithValue( "parmUser", WorkerID_.Text )
cmdInsert.Parameters.AddWithValue( "parmRole", "Worker" )
cmdInsert.Parameters.AddWithValue( "parmPwd", "12345" )
cmdInsert.Parameters.AddWithValue( "parmStatus", 1 )
Dim SqlUpdate As String
SqlUpdate = "INSERT INTO Worker (ID, WorkerID, WorkerName, DoB, Address, Phone, Email, CompanyName, PassportNum, PassportExp, VisaExp, VisaStatus, user_id) "
SqlUpdate &= " VALUES ( #parmID, #parmName, #parmDoB, etc... ) "
Dim cmdUpdate As New OleDbCommand(SqlUpdate, con.oleconnection)
cmdUpdate.Parameters.AddWithValue( "parmID", WorkerID_.Text )
cmdUpdate.Parameters.AddWithValue( "parmName", WorkerName.Text )
cmdUpdate.Parameters.AddWithValue( "parmDoB", DoB.Text )
-- etc with the rest of the parameters.
Final note. Make sure the data types you are trying to insert or update are of same type expected in the table. Such example is your "Birth Date" (DoB) field. If you are trying to insert as simple text, and it is not in an auto-converted format, the SQL-Insert might choke on it and fail. If you have a textbox bound to a DateTime type, then your parameter might be Dob.SelectedDate (such as a calendar control), or you could pre-convert from text to a datetime and then use THAT as your parameter value.
Other numeric values, leave as they are too, they should directly apply for the insert. You could also identify the AddWithValue() call the data type the parameter should represent (string, int, double, datetime, whatever)
You seem to have 12 parameters you wish to insert, and 13 arguments in the VALUES part of your insert query. is the Default seen in the values section below intentional?
INSERT INTO Worker (ID, ... VisaStatus) VALUES (default,"
ensure you have the correct number of parameters defined and added, then let us know, but i could be missing something else.

Error in my vb but correct in my sql query

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)

How to store checkboxlist all selected items into a database single column

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

SQL command will not insert into database

I'm trying to use a VB button to insert data into a database, but it keeps bringing up the error message I have in place for exceptions.
Can anyone help me with why this does not update the database?
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sql As String
Dim adapter As New SqlDataAdapter
Dim Customer As String = TextBox1.Text
Dim Product As String = TextBox2.Text
Dim Location As String = TextBox3.Text
Dim Details As String = TextBox4.Text
Dim Owners As String = DropDownList1.Text
Dim Urgency As String = DropDownList2.Text
connetionString = "Data Source=ZUK55APP02;Initial Catalog=BugFixPortal;User ID=SLC***;Password=rep***"
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details) VALUES ('" & Owners & ", " & Customer & ", " & Product & ", " & Location & ", " & Urgency & ", " & Details & "')"
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
adapter.UpdateCommand = sqlCnn.CreateCommand
adapter.UpdateCommand.CommandText = sql
adapter.UpdateCommand.ExecuteNonQuery()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
End Try
End Sub
I would not go down this road as your code is weak against SQL Injection
you should use parameters instead.Something like the below
c.Open();
string insertString = #"insert into YourTable(name, street, city,....) values(#par1, #par2, #parN,....)"
SqlCommand cmd = new SqlCeCommand(insertString, c);
cmd.Parameters.Add("#par1", SqlDbType.VarChar).Value = "MyName";
//etc
cmd.ExecuteNonQuery();
c.Close();
You are incorrectly quoting your values.
This string has an opening and closing single quote around ALL the values, which is incorrect.
VALUES ('" & Owners & ", " & Customer & ", " & Product & ", " & Location & ", " & Urgency & ", " & Details & "')"
Instead, put single quotes around character data, eg., if Product is a varchar, it would look like this:
VALUES (" & Owners & ", " & Customer & ", '" & Product & "', " & Location & ", " & Urgency & ", " & Details & ")"
The real problem, though, is that you should be using parameterized queries instead. This code is prone to SQL injection attacks.
Change this;
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
to Something like this;
MsgBox("Unable to update Database with Request - Please speak to Supervisor!" & ex.Message)
It will give you more details on the exception, however at a quick glance I can see a problem, the values you are trying to insert are strings, you've enclosed all your values in a single set of ' characters, rather than enclosing each string parameter in a pair of ' values, i.e.
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details) VALUES ('" & Owners & "', '" & Customer & "', '" & Product & "',' " & Location & "', '" & Urgency & "', '" & Details & "')"
You really should look at parameterizing your queries as you're wide open to SQL injection attacks. See HERE
In terms of your code itself, your SQL syntax is wrong as you need to put apostrophes around each value. Try this:
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details)
VALUES ('" & Owners & "', '" & Customer & "', '" & Product &
"', '" & Location & "', '" & Urgency & "', '" & Details & "')"
Here's an example using Parameters
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details)
VALUES ('#Owners', '#Customer', '#Product', '#Location', '#Urgency', '#Details')"
Then add parameters like so:
command.Parameters.AddWithValue("#Owners", Owners)
command.Parameters.AddWithValue("#Customer", Customer)
command.Parameters.AddWithValue("#Product", Product)
command.Parameters.AddWithValue("#Location", Location)
command.Parameters.AddWithValue("#Urgency", Urgency)
command.Parameters.AddWithValue("#Details", Details)
I think you want to use adapter.InsertCommand instead of adapter.UpdateCommand
in
Try
sqlCnn.Open()
adapter.UpdateCommand = sqlCnn.CreateCommand //(adapter.InsertCommand)
adapter.UpdateCommand.CommandText = sql //(adapter.InsertCommand)
adapter.UpdateCommand.ExecuteNonQuery() //(adapter.InsertCommand)
sqlCnn.Close()
Catch ex As Exception
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
End Try
and agree with parametrized sql query
see http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx for more infos