SYNTAX ERROR INSERT INTO STATEMENT Visual Basic - vb.net

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

Related

Delete record from SQL database in VB.NET

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

"variable" is not declared error

Image of the error
I am new to Vb.net programing and I need a little help here, I pretend to send info to my database, the first query gives me the id I need and I declare it as "postoid", when I later try to call it (in the insert into part) it says it is not declared, I have googled the problem a hundred times but I couldn't find the answer.
Ps: this code is all in the same private sub
Try
mysqlconn.Open()
queryrow = "Select * from postos where postos_nome ='" & TextBox1.Text & "'"
COMMANDuser1 = New MySqlCommand(queryrow, mysqlconn)
READERuser = COMMANDuser1.ExecuteReader
While READERuser.Read
Dim postoid = READERuser.GetString("postos_id")
End While
mysqlconn.Close()
Catch ex As Exception
End Try
Dim sqlquery As String = "INSERT INTO computadores VALUES (0,'" & pcname.ToUpper & "','" & ip & "','" & so & "','" & cpu & "','" & ram & "','" & gc & "','" & wserial & "','" & mnome & "','" & mserial & "','" & "--- ,,'Inativo','" & empresaid & "','" & postoid & "','" & userid & "')"
Dim sqlcommand As New MySqlCommand
With sqlcommand
.CommandText = sqlquery
.Connection = mysqlconn
.ExecuteNonQuery()
End With
MsgBox("Computador Adicionado")
Dispose()
Close()
Your variable postoid is out-of-scope outside the block it is declared in.
All you need to do is declare it outside the Try structure:
Dim postoid As String = ""
queryrow = "Select postos_id from postos where postos_nome = #PostosNome"
Using COMMANDuser1 As New MySqlCommand(queryrow, mysqlconn)
COMMANDuser1.Parameters.Add("#PostosNome", TextBox1.Text)
mysqlconn.Open()
READERuser = COMMANDuser1.ExecuteReader()
While READERuser.Read
postoid = READERuser.GetString("postos_id")
End While
mysqlconn.Close()
End Using
If postoid <> "" Then
' perform the insert...
I did not actually use Try in that, as you have no code in your Catch block - having no code in the Catch block has the effect of hiding errors. You want to see the errors.
For using SQL parameters, see, e.g., Inserting data into a MySQL table using VB.NET but please use .Add instead of .AddWithValue - the latter will not always work as intended.

Getting error while running the query [duplicate]

This question already has an answer here:
Why error ???? Syntax error in INSERT INTO statement
(1 answer)
Closed 7 years ago.
Here is my code.
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\speednet\speed_net.accdb")
Dim com As New OleDbCommand
con.Open()
com.Connection = con
com.CommandText = "insert into users (name,username,password,user_type) values ('" & name1.Text & "' ,'" & username.Text & "' ,'" & password.Text & "','" & account_type.Text & "')"
com.ExecuteNonQuery()
The error:
Syntax error in insert into statement ...
Cant find out the problem.
Password is a reserved keyword in access. You need square brackets around that word.
But your query should also be modified to use a parameter approach instead of string concatenation, otherwise more dangerous situation will be possible. Read about Sql Injection and what happen if one of your concatenated string contains a single quote.
So
Using con = New OleDbConnection("....")
Using com = New OleDbCommand("insert into users " & _
"(name,username,[password],user_type) " & _
"values (#name, #uname,#pass,#acctype)", con)
con.Open()
com.Parameters.AddWithValue("#name", name1.Text)
com.Parameters.AddWithValue("#uname", username.Text)
com.Parameters.AddWithValue("#pass", password.Text)
com.Parameters.AddWithValue("#acctype", account_type.Text)
com.ExecuteNonQuery()
End Using
End Using

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

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