Syntax error in 'INSERT INTO' statement VB.NET ACCESS - sql

I'm trying to insert a record into a database using VB.NET using this line but I am given a syntax error? I don't see anything wrong with it I think?
SQL = ("INSERT INTO Orders (Items, CustName, Table, Cost, Price)
VALUES ('" & ItemsString & "', '" & CustName & "', '" & Table &
"', '" & Cost & "', '" & Price & "');")

I am not sure what the parentheses outside the string are for but they are not necessary. Always use parameters. Never concatenate strings to build CommandText.
Please note that TABLE is a reserved word. Enclosed in brackets.
I had to guess the datatypes for the parameters. Check your database for correct values. Money should be Decimal.
This is what a parametrized query should look like.
Private Sub InsertRecord(ItemsString As String, CustName As String, Table As String, Cost As Decimal, Price As Decimal)
Dim SQL = "INSERT INTO Orders (Items, CustName, [Table], Cost, Price) VALUES (#ItemsString, #CustName, #Table, #Cost, #Price);"
Using cn As New OleDbConnection("Your conneciton string"),
cmd As New OleDbCommand(SQL, cn)
cmd.Parameters.Add("#ItemsString", OleDbType.VarChar).Value = ItemsString
cmd.Parameters.Add("#CustName", OleDbType.VarChar).Value = CustName
cmd.Parameters.Add("#Table", OleDbType.VarChar).Value = Table
cmd.Parameters.Add("#Cost", OleDbType.Decimal).Value = Cost
cmd.Parameters.Add("#Price", OleDbType.Decimal).Value = Price
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub

Related

vb.net sql parameter incorrect syntax near 'value'

I'm new here, I'm trying to convert an integer into varbinary to insert into an already made SQL table. I've included the code, I get incorrect syntax near "523641" which is the HOUSE_ID I am trying to convert.
I also converted the int to byte array and added a parameter to the command but same result
Dim varbin As String = " convert(varbinary, '" & houseid & "')"
obj = objCon.CreateCommand()
strSQL = "insert into " & tbl & " (hello, HOUSE_ID, world) VALUES ('" & hello & "','" & varbin & "','" & world & "')"
obj.CommandText = strSQL
obj.ExecuteNonQuery()
Expected result is putting that 523641 into the varbinary(50) column.
Not sure why you would want to store an integer in a varbinary column but you can use BitConverter along with a parameterized query. Always use parameters instead of string concatenation for values that vary by execution as parameters have a number of benefits for security, performance, and ease of use.
Dim varbin As Byte() = BitConverter.GetBytes(houseid)
obj = objCon.CreateCommand()
strSQL = "insert into " & tbl & " (hello, HOUSE_ID, world) VALUES (#hello, #varbin, #world);"
obj.Parameters.Add("#hello", SqlDbType.VarChar, 50).Value = hello
obj.Parameters.Add("#varbin", SqlDbType.VarBinary, 50).Value = varbin
obj.Parameters.Add("#world", SqlDbType.VarChar, 50).Value = world
obj.CommandText = strSQL
obj.ExecuteNonQuery()

INSERT INTO and UPDATE SQL using visual basic into access database

I'm working on my A Level coursework using VB forms as my front end and an Access database as the back end. I've tried loads of different ways but I can't get the program to update or insert data into the database.
I know for a fact the connection is fine because I've had no problem retrieving data from access into the program.
This the code for one of the forms:
(the database connection is in a separate form)
Access.ExecQuery("SELECT * FROM Exam;")
Dim user As String = TxtStudent.Text
Dim board As String = CmbBoard.Text
Dim instrument As String = CmbInstrument.Text
Dim grade As String = CmbGrade.Text
Dim result As String = CmbResult.Text
Access.ExecQuery("INSERT INTO Grade (Username, Instrument, Exam Board, Grade, Result) VALUES ('" & user & "', '" & board & "', '" & instrument & ", " & grade & ", " & result & "');")
If Not String.IsNullOrEmpty(Access.Exception) Then MsgBox(Access.Exception) : Exit Sub
The error message says there is a syntax error on INSERT INTO statement.
Am i just being really stupid?
you are missing closing "'" for instrument '" & instrument & "', " . and also, just confirm the values for fields without single quotes(grade ) are numeric otherwise add single quotes
Your single and double parenthesis are a bit of a mess. This alone is a good reason to use parameters but it also protects you from malicious input by users. The important thing with Access is that you must add the parameters in the same order that the command uses them.
Dim cn As New OleDbConnection("Your Access connection string")
Dim s As String = "INSERT INTO Grade (Username, Instrument, Exam Board, Grade, Result) VALUES (#User, #Instrument, #Board, #Grade, #Result);"
Dim cmd As New OleDbCommand(s, cn)
cmd.Parameters.AddWithValue("#User", TxtStudent.Text)
cmd.Parameters.AddWithValue("#Instrument", CmbInstrument.Text)
cmd.Parameters.AddWithValue("#Board", cmdBoard.Text)
cmd.Parameters.AddWithValue("#Grade", CmdGrade.Text)
cmd.Parameters.AddWithValue("#Result", CmdResult.Text)
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Double check the data types of the fields and adjust the code if they are not all strings.
In SQL Queries and statements , '(single quote) is used to pass a value of type string to any given parameter(or anything).You mistake was that you forgot to add ' in all the places.
"INSERT INTO Grade (Username, Instrument, Exam Board, Grade, Result) VALUES ('" & user & "', '" & board & "', '" & instrument & ", "'" & grade & "'", "'" & result & "'")"
This will solve it :)
However, one advice, don't give direct values in the statement itself,you are welcoming SQL-Injection.Rather,create parameters and values to them later :
Dim cmd as New SqlCommand("INSERT INTO Grade (Username)Values(#uname)",con)
cmd.Parameter.Add("#uname",SqlDbType.Vachar) = "abc"
Hope this helps to enrich your knowledge :)
You must try this!
Dim con As New OleDbConnection("Your Access connection string here")
Dim s As String = "INSERT INTO Grade ([Username], [Instrument], [Exam Board], [Grade], [Result]) VALUES (#User, #Instrument, #Board, #Grade, #Result)"
Dim cmd As New OleDbCommand(s, con)
con.Open()
cmd.Parameters.AddWithValue("#User", TxtStudent.Text)
cmd.Parameters.AddWithValue("#Instrument", CmbInstrument.Text)
cmd.Parameters.AddWithValue("#Board", cmdBoard.Text)
cmd.Parameters.AddWithValue("#Grade", CmdGrade.Text)
cmd.Parameters.AddWithValue("#Result", CmdResult.Text)
cmd.ExecuteNonQuery()
con.Close()
I hope it will works! :)
Dim con As New OleDbConnection("Your Access connection string here")
Dim s As String = "INSERT INTO Grade ([Username], [Instrument], [Exam Board], [Grade], [Result]) VALUES (#User, #Instrument, #Board, #Grade, #Result)"
Dim cmd As New OleDbCommand(s, con)
con.Open()
cmd.Parameters.AddWithValue("#User", TxtStudent.Text)
cmd.Parameters.AddWithValue("#Instrument", CmbInstrument.Text)
cmd.Parameters.AddWithValue("#Board", cmdBoard.Text)
cmd.Parameters.AddWithValue("#Grade", CmdGrade.Text)
cmd.Parameters.AddWithValue("#Result", CmdResult.Text)
cmd.ExecuteNonQuery()
con.Close()

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

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