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()
Related
I want to delete a record which is related to the SerialNo in the database.
This is my code:
Using con = New MySqlConnection("server=" & server & ";" & "user id=" & userid & ";" & "password=" & password & ";" & "database=" & database)
con.Open()
Dim sqlText = "DELETE * FROM datatable WHERE SerialNo = #ulogin"
Using cmd = New MySqlCommand(sqlText, con)
cmd.Parameters.AddWithValue("#ulogin", frmmain.txtinput.Text)
cmd.ExecuteNonQuery()
End Using
con.Close()
End Using
This code doesn't work. When I run the program, the following error appears:
Please be kind enough to suggest a suitable solution.
NOTE: 221 means the entered number.
The * does not belong. You can't delete only specific columns from a record. You either delete the whole record or do nothing, and so there is no column list portion to a DELETE statement.
While I'm here, there's no need to call con.Close() (the Using block takes care of that for you) and it's better to avoid AddWithValue() in favor of an Add() overload that lets you be explicit about your parameter type.
Const sqlText As String = "DELETE FROM datatable WHERE SerialNo = #ulogin"
Using con As New MySqlConnection("server=" & server & ";" & "user id=" & userid & ";" & "password=" & password & ";" & "database=" & database), _
cmd AS New MySqlCommand(sqlText, con)
cmd.Parameters.Add("#ulogin", MySqlDbType.Int32).Value = frmmain.txtinput.Text
con.Open()
cmd.ExecuteNonQuery()
End Using
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.
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
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
I am trying to export some data from a SQL Express table to Access using VB.net. The data is correctly displayed in SQL as, for example, temperature with the small degree object and the letters F or C for Farenhiet or Celsius. The character is of course represented by ° = "°" in html code, which is what appears in my access tables.
How can I get the insert statements to correctly pass this symbol? I have thousands of records and this applies to maybe a hundred or so in each of a few hundred DB's I am running this conversion on.
I read the data from a Gridview an .aspx .net web page and then use an insert query with an Access OLEDB connection.
SQLString1 = "INSERT INTO tblFornStrings (Str_ID, Code, Str_Name, Srt_Text, Lng_Text, Alt_Text) "
SQLString1 = SQLString1 & "VALUES ('" & StrngID & "', "
SQLString1 = SQLString1 & "'" & Code & "',"
SQLString1 = SQLString1 & "'" & Str_Name & "',"
SQLString1 = SQLString1 & "'" & newText1 & "',"
SQLString1 = SQLString1 & "'" & newText2 & "',"
SQLString1 = SQLString1 & "'" & newText3 & "')"
' SQLString1 = SQLString1 & "'" & tblSource & "')"
Dim dbCommand1 = New OleDbCommand(SQLString1, pConn)
pConn.Open()
dbCommand1.ExecuteNonQuery()
dbCommand1 = Nothing
These are the two fields that have the data, newText1 = Srt_Text, newText2 = Lng_Text
I have now tried to make this a parameterized query, having read that it would allow the string to be copied without an encoding issue. It did not work. Here is another version of the INSERT code using the parameters.
Dim SqlString As String = "INSERT INTO Strings (Str_ID, Code, Str_Name, Srt_Text, Lng_Text, Alt_Text) Values (?,?,?,?,?,?)"
Using cmd As New OleDbCommand(SqlString, pConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("Str_ID", StrngID)
cmd.Parameters.AddWithValue("Code", Code)
cmd.Parameters.AddWithValue("Str_Name", Str_Name)
cmd.Parameters.AddWithValue("Srt_Text", newText1)
cmd.Parameters.AddWithValue("Lng_Text", newText2)
cmd.Parameters.AddWithValue("Alt_Text", newText3)
pConn.Open()
cmd.ExecuteNonQuery()
pConn.Close()
End Using
The output is the same as is dispalyed in the graphic for the output of the first code block.
Thanks for any suggestions.
So you have some strings extracted from Gridview, and so far you were using those strings "as is" to build SQL statements (or to set parameter values for a parameterized database command). Now, what happens if, instead of using them "as is" you'd decode them first - e.g. by passing them to HttpUtility.HtmlDecode(...) method? (See this MSDN page for more details.)