Syntax Error in Insert Statement - vb.net

I'm new to Database connection and when I am having a problem with the cmdInsert.ExecuteNonQuery() line it says there is a syntax error with the INSERT INTO statement and I can't figure out what the problem is:
Imports System.Data
Imports System.Data.OleDb
Public Class txtNotes
Dim cnnOLEDB As New OleDbConnection
Dim cmdInsert As New OleDbCommand
Dim strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & System.Environment.CurrentDirectory & "\CourseworkDB"
'the name of the database goes in here'
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cnnOLEDB.ConnectionString = strConnectionString
cnnOLEDB.Open()
End Sub
Private Sub AddFirstName_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddFirstName.Click
If txtFirstName.Text <> "" Then
MsgBox(cmdInsert.CommandText)
cmdInsert.CommandText = "INSERT INTO Customer (First Name) VALUES (" & txtFirstName.Text & ", '"
cmdInsert.CommandType = CommandType.Text
cmdInsert.Connection = cnnOLEDB
cmdInsert.ExecuteNonQuery()
Else
MsgBox("Enter the required values:" & vbNewLine & "1. First Name")
End If
cmdInsert.Dispose()
End Sub
End Class

I Strongly suggest not getting into a routine of building SQL strings by concatinating strings together. You are leaving yourself wide open to SQL-Injection, especially if this is web based. You should build your commands with place-holder parameters in the string, then add the parameters to the command object. Add the parameters in the same sequence as they would appear in the command... such as
cmdInsert.CommandText = "INSERT INTO Customer (FirstName, LastName) VALUES ( #parmFirstName, #parmLastName )"
cmdInsert.Parameters.AddWithValue( "#parmFirstName", txtFirstName.Text );
cmdInsert.Parameters.AddWithValue( "#parmLastName", txtLastName.Text );
If your field names have embedded spaces, different databases work
differently, some requires single backtick (the key left of the number
1) around the field. such as 'first name'. Some use square brackets,
such as [first name].

Try this
"INSERT INTO Customer (First Name) VALUES ('" & txtFirstName.Text & "')"

Warning: Bobby is watching you.
cmdInsert.CommandText = _
"INSERT INTO Customer (First Name) VALUES ('" & txtFirstName.Text & "')"

Related

error in Inserting data in database

Problem : Inserting data into database.
Error:
SQLException was unhandled by the user
Incorrect Syntax near the keyword 'User'
the one the I put arrow is the line that is highlighted seems it was the error i'm not sure.
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data.SqlClient
Imports System.Configuration
Partial Public Class _Default
Inherits System.Web.UI.Page
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
con.Open()
End Sub
Protected Sub addBTN_Click(ByVal sender As Object, ByVal e As EventArgs) Handles addBTN.Click
Dim cmd As New SqlCommand("insert into User (Name, Gender, Age) values ('" & nameTB.Text & "', '" & genderTB.Text & "', '" & ageTB.Text & "')", con)
cmd.ExecuteNonQuery() <------------------------------
con.Close()
nameTB.Text = ""
genderTB.Text = ""
ageTB.Text = ""
End Sub
End Class
User is a reserved word so needs to be in square brackets. Your query is open to SQL injection so needs to be parameterized. I would advise opening the connection just before you need it. Also use the Using statement will take care of closing and disposal for you.
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Using cmd As New SqlCommand("insert into [User] (Name, Gender, Age) values (#nameTB, #genderTB,#ageTB)", con)
cmd.Parameters.AddWithValue("#nameTB", nameTB.Text)
cmd.Parameters.AddWithValue("#genderTB", genderTB.Text)
cmd.Parameters.AddWithValue("#ageTB", ageTB.Text)
cmd.CommandType = CommandType.Text
con.Open()
cmd.ExecuteNonQuery()
nameTB.Text = ""
genderTB.Text = ""
ageTB.Text = ""
End Using
End Using
User is a reserved word. Enclose the word with square brackets:
Dim cmd As New SqlCommand("insert into [User] (Name, Gender, Age) values ('" & nameTB.Text & "', '" & genderTB.Text & "', '" & ageTB.Text & "')", con)
Source: https://stackoverflow.com/a/6082422/1271037

VB 2010 Express connected to database microsoft access 2010

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim sqlquery As String = "INSERT INTO Table1(Customer Name,Address,Contact Number,Type Of Customer)VALUES('" & TextBox1.Text & "', '" & TextBox2.Text & "', '" & TextBox3.Text & "','" & TextBox4.Text & "')"
Dim sqlcommand As New OleDbCommand
With sqlcommand
.CommandText = sqlquery
.Connection = con
.ExecuteNonQuery()
End With
MsgBox("ONE RECORD SUCCESFULLY ADDED :)")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Can somebody help me? It says that there is an error in INSERT INTO statement, i dont know why. Thanks for the help.
Try putting [] around column names that contain a space.
( [Customer Name], Address, [Contact Number], [Type Of Customer] )
It is important to enclose your field in [your field] when they have spaces in them, else it considers it as two fields and search for separator which there is none in this case.
hopes my answers helps a little.

Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'

Hi I have an invalid sql statement error. This is my code:
Imports System.Data.OleDb 'For OleDbConnection 
Imports System.Data 'For ConnectionState 
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub btnInsert_Click(sender As Object, e As EventArgs) Handles btnInsert.Click
'1 declare the variables
Dim strName As String = txtName.Text
Dim strAddress As String = txtAddress.Text
'2. creates a new connection to your DB.
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\GT\Documents\Database11.accdb'")
If conn.State = ConnectionState.Open Then
conn.Close()
End If
'3. open the connection to your DB. 
conn.Open()
'4. assign your SQL statement into sqlString variable. 
Dim sqlString As String
sqlString = "INSERT INTO tblStuInfo (stuName, stuAddress) VALUES ('" & strName & "' , '" & strAddress & "')"
'5. create a new command that links your SQL statement with your connection. 
Dim sqlcommand As New OleDbCommand(sqlString, conn)
'6. execute your command.
sqlcommand.ExecuteNonQuery()
End Sub
End Class
What is the problem? The path of the database and the table name of the DB is correct. Please help!
try to replace
sqlString = "INSERT INTO tblStuInfo (stuName, stuAddress) VALUES ('"
& strName & "' , '" & strAddress & "')"
with
sqlString = "INSERT INTO tblStuInfo (stuName, stuAddress) VALUES ('"
& strName.Replace("'", "''") & "' , '" & strAddress.Replace("'", "''") & "')"
this should solve any SQL injection issue, that happen when your string contain the ' character.
Anyway, I think you should add (or use) a key in the underlying table, otherwise how are you going to get these values back?

VB2010 database insert query throwing exception error

I am a new user to VB.net ( of 2 weeks ) and coming from a php background, am finding it tough going. I have created a small form that should insert some data into an access mdb database. However, I keep getting an error of:
System.Data.OleDb.OleDbException
I have outlined in my pasted code where this error is occurring and would be grateful if someone could point out where I have gone wrong. many thanks.
Imports System.Data.OleDb
Public Class frmMain
Dim strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\domain\storage1.mdb"
Dim cnnOLEDB As New OleDbConnection(strConnectionString)
Dim cmdOLEDB As New OleDbCommand
Dim cmdInsert As New OleDbCommand
Dim cmdUpdate As New OleDbCommand
Dim cmdDelete As New OleDbCommand
Dim cmd As OleDbCommand
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub btnInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
Dim first, last As String
Dim age As Integer
first = txtFirstName.Text
last = txtLastName.Text
age = txtAge.Text
Dim InsertQuery As String
InsertQuery = "INSERT INTO Details (first,last,age) VALUES ('" & first & "','" & last & "','" & age & "')"
cnnOLEDB.Open()
Dim cmd As OleDbCommand = New OleDbCommand(InsertQuery, cnnOLEDB)
cmd.Parameters.AddWithValue("first", txtFirstName.Text)
cmd.Parameters.AddWithValue("last", txtLastName.Text)
cmd.Parameters.AddWithValue("age", txtAge.Text)
cmd.ExecuteNonQuery() <--- ERROR
cnnOLEDB.Close()
MessageBox.Show("Insert complete.")
End Sub
End Class
The problem is here:
InsertQuery = "INSERT INTO Details (first,last,age) VALUES ('" & first & "','" & last & "','" & age & "')"
cmd.Parameters.AddWithValue("first", txtFirstName.Text)
cmd.Parameters.AddWithValue("last", txtLastName.Text)
cmd.Parameters.AddWithValue("age", txtAge.Text)
Try this:
InsertQuery = "INSERT INTO Details (first,last,age) VALUES (#first, #last, #age)"
Then for the Parameters:
cmd.Parameters.AddWithValue("#first", txtFirstName.Text)
cmd.Parameters.AddWithValue("#last", txtLastName.Text)
cmd.Parameters.AddWithValue("#age", txtAge.Text)
You can then remove these lines as you don't need them:
Dim first, last As String
Dim age As Integer
first = txtFirstName.Text
last = txtLastName.Text
age = txtAge.Text
First and Last are reserved words for Jet 4.0. They should not be used as column names. Access itself will let you get away with it, SQL code is a little less forgiving. If you can't avoid using those words, try putting them in square brackets [first] when addressing them. For more information on reserved words, see http://support.microsoft.com/kb/248738.

Syntax error in UPDATE statement access database in vb.net

I have just started learning VB.net for several weeks. i want to make a form and send data from a text box to a specific cell in ms access database (*.accdb) file. but the code i have writen gives the following error:
Syntax error in UPDATE statement.
i have checked several books and spent hours on internet, but no answer!
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim cnn1 As New OleDb.OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=
E:\Ebook\hararat\GUI\Heat Exchanger Designer\heat.accdb"
con.Open()
sql = "SELECT * FROM flow1"
da = New OleDbDataAdapter(sql, con)
da.Fill(ds, "flow1")
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("flow1").Rows(1).Item(1) = "name"
da.Update(ds, "flow1")
con.Close()
You need to use the .QuotePrefix and .QuoteSuffix properties of the OleDbCommandBuilder to wrap table and field names in square brackets. That is, instead of just
Dim cb As New OleDb.OleDbCommandBuilder(da)
you need to do
Dim cb As New OleDb.OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
That will generate an UPDATE statement of the form
UPDATE [TableName] SET [ColumnName]= ...
which is necessary if the table name or any of the field names happen to be reserved words in Access SQL.
Try this one
dim sqlupdate as string = "UPDATE tablename SET column_name = '" & textname.text & "' WHERE column_name = '" & textname.text & "'"
Sometimes errors occur when using the following column names: Username, Password, Date, Time, and much more of this type, try to avoid these column names because this might cause the problem of your issue regarding updating tables. Enable for you to update this kind of column name you need to enclose it with [ and ] so it comes like this: [Username], [Date], etc. so the syntax might go like this:
UPDATE tablename SET [Username] = '" & textname.text & "' WHERE column_name = '" & textname.text & "'"
my codes goes like this:
Open_Con()
Dim sqlUpdate As String
Dim sqlUpdatePass As DialogResult
sqlUpdate = "UPDATE tblAccounts SET [Password] = '" & txtRPassword.Text & "' WHERE [Username] = '" & txtUsername.Text & "'"
sqlCmd = New OleDbCommand(sqlUpdate, sqlCon)
Try
sqlUpdatePass = MessageBox.Show("Are you sure to save this changes?", "Save changes?", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If sqlUpdatePass = vbYes Then
sqlCmd.ExecuteNonQuery()
MsgBox("Changes are now saved", MsgBoxStyle.Information, "New password has been set.")
Call ClearAll()
Me.Hide()
Else
Exit Sub
End If
Catch ex As Exception
MsgBox("Could not perform this task because " & ex.Message, MsgBoxStyle.Exclamation, "Error")
End Try
sqlCmd = Nothing
sqlCon.Close()
hope this things mention above codes helps your problem. have a nice day and happy coding :)
dim sqlupdate as string="UPDATE [tablename] SET [column_name] = '"& textname.text &"' WHERE [column_name] = '"& textname.text &"';"
By enclose attributes with square brackets, it appears to work I have tried it, it works
Imports System.Data.OleDb
Imports System.Data
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Database2DataSet.identitas' table. You can move, or remove it, as needed.
Me.IdentitasTableAdapter.Fill(Me.Database2DataSet.identitas)
End Sub
Public Sub clean()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
End Sub
Public Sub read()
Call openconn()
str = "select * from identitas"
dtadapter = New OleDbDataAdapter(str, con)
Dim dg As New DataTable
dg.Clear()
dtadapter.Fill(dg)
dgv.DataSource = dg
End Sub
Public Sub create()
Call openconn()
str = "insert into identitas values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "') "
cmd = New OleDbCommand(str, con)
cmd.Connection = con
cmd.ExecuteNonQuery()
MsgBox("data lebet")
read()
clean()
End Sub
Public Sub update()
Call openconn()
str = "UPDATE identitas SET [Nama] = '" & TextBox2.Text & "',[Alamat] = '" & TextBox3.Text & "', [No] = '" & TextBox4.Text & "' where [NIK] = '" & TextBox1.Text & "'"
cmd = New OleDbCommand(str, con)
cmd.Connection = con
cmd.ExecuteNonQuery()
MsgBox("data ter ubah")
clean()
read()
End Sub
Public Sub delete()
Call openconn()
str = "delete from identitas where NIK = '" & TextBox1.Text & "'"
cmd = New OleDbCommand(str, con)
cmd.Connection = con
cmd.ExecuteNonQuery()
clean()
End Sub
Private Sub btnclose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclose.Click
Me.Close()
End Sub
Private Sub btnc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnc.Click
create()
End Sub
Private Sub btnr_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnr.Click
read()
End Sub
Private Sub btnclean_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclean.Click
clean()
End Sub
Private Sub btnd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnd.Click
Dim pesan As String = MsgBox("yakin mau hapus = " & TextBox1.Text & "?", MsgBoxStyle.YesNo)
If pesan = vbYes Then
delete()
End If
read()
End Sub
Private Sub btnu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnu.Click
update()
End Sub
End Class
I had same problem, this helped.
"Sometimes errors occur when using the following column names: Username, Password, Date, Time, and much more of this type, try to avoid these column names because this might cause the problem of your issue regarding updating tables. Enable for you to update this kind of column name you need to enclose it with [ and ] so it comes like this: [Username], [Date], etc. so the syntax might go like this: "
I renamed the columns in Access (e.g Password1,Username1) as the same words password, username might be reserved in vb.net. Thanks for this response.