How to store checkboxlist all selected items into a database single column - vb.net

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

Related

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.

SYNTAX ERROR INSERT INTO STATEMENT Visual Basic

Why am I getting this error
Syntax error INSERT INTO statement
Please help! Thanks in advance!
Dim cmd As New OleDb.OleDbCommand
If TabControl1.SelectedIndex = 0 Then
If Not cnn.State = ConnectionState.Open Then
'open connection if it is not yet open
cnn.Open()
End If
cmd.Connection = cnn
'check whether add new or update
If Me.txtStdID.Tag & "" = "" Then
'add new
'add data to table
cmd.CommandText = "INSERT INTO Student (StudentID, LastName, FirstName, MiddleInitial, Grade, Section, ContactNumber, AdviserID, CounselorID, ParentName)" & _
"VALUES('" & Me.txtStdID.Text & "','" & Me.txtLname.Text & "','" & _
Me.txtFname.Text & "','" & Me.txtMidInt.Text & "','" & _
Me.txtGrade.Text & "','" & Me.txtSection.Text & "','" & Me.txtContact.Text & "','" & _
Me.txtAdvID.Text & "','" & Me.txtConID.Text & "','" & Me.txtPname.Text & "')"
cmd.ExecuteNonQuery()
Well, this is a well known problem. Databases define many words as "reserved keywords", and if they are used for column names or table names, they need to be enclosed in the appropriate quoting character for your database.
Seeing that you are using an OleDbConnection I assume that you are using MS-Access as database. In that case the list of reserved keywords could be found here,
And indeed SECTION is a reserved keyword, so your query, should be written as
"INSERT INTO Student (......, [Section], ......
Said that, let's say something about string concatenation to build an SQL Query.
It's bad, bad, bad.... There are numerous problem with that. For example, what happens if one of your fields contains a single quote? The whole query will fail again with a Syntax error. Also, albeit more difficult to exploit with Access because it doesn't support multiple command texts there is the problem of SQL Injection to avoid at all costs. You need to learn how to use a PARAMETERIZED QUERY
Dim sqlText = "INSERT INTO Student (StudentID, LastName, FirstName, " & _
"MiddleInitial, Grade, [Section], ContactNumber, AdviserID, " & _
"CounselorID, ParentName) VALUES (?,?,?,?,?,?,?,?,?,?)"
If TabControl1.SelectedIndex = 0 Then
Using cnn = New OleDbConnection(...constring here....)
Using cmd = new OleDbCommand(sqlText, cnn)
cnn.Open()
cmd.Parameters.Add("#p1", OleDbType.VarWChar).Value = Me.txtStdID.Text
cmd.Parameters.Add("#p2", OleDbType.VarWChar).Value = Me.txtLname.Text
.... and so on with the other parameters ....
.... strictly following the order of the fields in the insert....
cmd.ExecuteNonQuery()
End Using
End Using

execute multiple command for update vb.net

i am working on a vb project . in this i need to save some record to one table and update some records in another table in one event or click .. i am doing like this .
dim simpan as new sqlcommand
conn = New SqlConnection(connectionstring)
conn.Open()
simpan = New SqlCommand()
simpan.Connection = conn
simpan.CommandType = CommandType.Text
simpan.CommandText = "update barang set (nama_barang,harga)values(" & TextBox3.Text & ",'" & TextBox4.Text & "') where kode_barang = '" & TextBox2.Text & "'"
simpan.ExecuteNonQuery()
tampil()
MsgBox("Data Berhasil Diubah", MsgBoxStyle.Information, "Informasi")
conn.Close()
but it giving error as "incorrect syntax near '('" .. i am not getting where i go wrong .. please help me
I see a couple issues with this...
Your Syntax is wrong on your update statement (Al-3sli beat me to that one).
Your textbox values will cause issues if a user types a single quote in the text box (For Example: The word "Wasn't".
Add the replace function to each textbox TextBox3.text.Replace("'","''") That will replace single ticks with two single ticks.
You might also consider using parameterized queries
You can't use update like this, change your code like so:
simpan.CommandText = "update barang set nama_barang = '" & TextBox3.Text & "',harga ='" & TextBox4.Text & "' where kode_barang = '" & TextBox2.Text & "'"
simpan.ExecuteNonQuery()

VB.net Access Update Query

VB.net access update query is giving a Syntax Error in Update Query Error. My query is as follows:
query = "UPDATE users SET username='" & newUsername & "', password='" & newPassword & "', department='" & newDepartment & "', display_name='" & newDisplayName & "', email='" & newEmail & "', extension='" & newExtension & "', access_level='" & newAccessLevel & "' WHERE id=" & usrID
None of the above variables have any symbols at all. What am I doing wrong?
::UPDATE::
UPDATE users SET username='alison', password='farm1234',department='1',display_name='Alison *****', email='production#**********.com', extension='1012',access_level='50' WHERE id=1
This is what the query runs as.
The error is caused by the usage of the reserved keyword PASSWORD without enclosing it in square brackets.
Said that, you never use string concatenation to build sql commands, but always a parameterized query to avoid Sql Injection problems but also syntax error in parsing text values (containing single quotes) or decimal values with their decimal separators or dates values.
So, a possible approach to your task could be
query = "UPDATE users SET username=?, [password]=?, department=?, " & _
"display_name=?, email=?, extension=?, access_level=?" & _
" WHERE id=?"
Using cmd = new OleDbCommand(query, connection)
cmd.Parameters.AddWithValue("#p1", newUsername)
cmd.Parameters.AddWithValue("#p2", newPassword)
cmd.Parameters.AddWithValue("#p3", newDepartment)
cmd.Parameters.AddWithValue("#p4", newDisplayName)
cmd.Parameters.AddWithValue("#p5", newEmail)
cmd.Parameters.AddWithValue("#p6", newExtension)
cmd.Parameters.AddWithValue("#p7", newAccessLevel)
cmd.Parameters.AddWithValue("#p8", usrID)
cmd.ExecuteNonQuery()
End Using
Keep in mind that OleDb doesn't use the parameter names to find the corresponding placeholder in sql command text. Instead it uses a positional progression and thus adding the parameters to the collection should respect the order in which the parameter appears in the sql command text
ConStr()
Qry="UPDATE users SET username=#uname, [password]=#pass, department=#dept, " & _
"display_name=#dnam, email=#email, extension=#ext, access_level=#acslvl" & _
" WHERE id=#id"
cmd = new oledbcommand(Qry,Conn)
cmd.Parameters.AddWithValue("#uname",newUsername)
cmd.Parameters.AddWithValue("#pass",newPassword)
cmd.Parameters.AddWithValue("#dept",newDepartment)
cmd.Parameters.AddWithValue("#dnam",newDisplayName)
cmd.Parameters.AddWithValue("#email",newEmail)
cmd.Parameters.AddWithValue("#ext",newExtension)
cmd.Parameters.AddWithValue("#acslvl",newAccessLevel)
cmd.Parameters.AddWithValue("#id",usrID)
cmd.ExecuteNonQuery()

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