system.data.oledb.oledbexception:Syntax error in INSERT INTO Statement - sql

I have a Project in VB.NET as follows
Public Class MCARegis
Dim con As New OleDb.OleDbConnection()
Private Sub MCARegis_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim da As OleDb.OleDbDataAdapter
Dim dbprovider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Taher\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\Database1.accdb;Persist Security Info=False;"
Me.con = New OleDb.OleDbConnection()
con.ConnectionString = dbprovider
con.Open()
MsgBox("opened")
End Sub
Private Sub btnadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnadd.Click
Try
Dim da As OleDb.OleDbDataAdapter
Dim dbprovider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Taher\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\Database1.accdb;Persist Security Info=False;"
Me.con = New OleDb.OleDbConnection()
con.ConnectionString = dbprovider
con.Open()
Dim sqlquery As String = "INSERT INTO MCA (URno,SName,Fname,CAddress,)" + "VALUES (" & CInt(txtUrn.Text) & ",'" & txtName.Text & "','" & txtFname.Text & "','" & txtCAdd.Text & "');"
Dim sqlcommand As New OleDb.OleDbCommand(sqlquery)
With sqlcommand
.CommandText = sqlquery
.Connection = con
.ExecuteNonQuery()
End With
MsgBox("Record Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
I am getting an error when i try to add values at the Insert into statement any suggestions on this?
system.data.oledb.oledbexception:Syntax error in INSERT INTO Statement at system.data.oledb.command.exceutecommandtexterrorhandling(oledbhresult hr)
at systems.data.oledb.oledbcommand.executecommandtext(object&executeresult)......
at system.data.oledb.oledbcomamand.executenonquery()
at line 29.
Thanks in Advance....

Replace "INSERT INTO MCA (URno,SName,Fname,CAddress,)" by "INSERT INTO MCA (URno,SName,Fname,CAddress)". You have specified a redundant comma

Related

data type mismatch criteria expression in vb.net,access while inserting

Imports System.Data.OleDb
Imports System.IO
Public Class insuranceform
Dim read As String
Dim datafile As String
Dim connstring As String
Dim cmd As New OleDbCommand
Public da As New OleDbDataAdapter
Dim str As String
Public ds As New DataSet
Public ds1 As New DataSet
Public ds2 As New DataSet
Dim myconnection As OleDbConnection = New OleDbConnection
Dim er As Integer
Private Sub insuranceform_Load(sender As Object, e As EventArgs) Handles MyBase.Load
read = "provider=microsoft.ace.oledb.12.0;data source="
datafile = "C:\Users\DELL\source\repos\HRIS SYSTEM\loginformdatabase\BLUESTREAM.accdb"
connstring = read & datafile
myconnection.ConnectionString = connstring
ds.Clear()
DateTimePicker1.Value = DateTime.Now
DateTimePicker2.Value = DateTime.Now
DateTimePicker3.Value = DateTime.Now
If myconnection.State = ConnectionState.Open Then
myconnection.Close()
End If
myconnection.Open()
er = 0
'cn.Open()
str = "select * from insurancedetail"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "insurancedetail")
End Sub
Private Sub Save_Click(sender As Object, e As EventArgs) Handles Button1.Click
ds.Clear()
str = "select * from insurancedetail"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "insurancedetail")
If er = 0 Then
Try
cmd.Connection = myconnection
cmd.CommandText = "insert into insurancedetail(Name,EmployeeID,PAN,UniversalAccountNumber,AdharNo,CurrentAddress,PermanentAddress,Landline,MartialStatus,MobileNumber,EmergencyContactNo,BloodGroup,DoyouHaveHDFCbankaccount,NameOfdependentmember_F) values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "','" & TextBox7.Text & "','" & TextBox8.Text & "','" & ComboBox2.Text & "','" & TextBox9.Text & "','" & TextBox10.Text & "','" & TextBox11.Text & "','" & ComboBox1.Text & "','" & TextBox12.Text & "')"
cmd.ExecuteNonQuery() 'if command is executed'
Dim result As Integer = MessageBox.Show("New insurance detail Added. Want To Add Another One.", "Added", MessageBoxButtons.YesNo)
If result = DialogResult.No Then
Me.Close()
ElseIf result = DialogResult.Yes Then
ds.Clear()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
TextBox9.Clear()
TextBox10.Clear()
TextBox11.Clear()
TextBox12.Clear()
TextBox13.Clear()
TextBox14.Clear()
TextBox15.Clear()
TextBox16.Clear()
TextBox17.Clear()
TextBox18.Clear()
TextBox20.Clear()
ComboBox1.ResetText()
ComboBox2.ResetText()
ComboBox3.ResetText()
ComboBox4.ResetText()
ComboBox5.ResetText()
DateTimePicker1.ResetText()
DateTimePicker2.ResetText()
DateTimePicker3.ResetText()
str = "select * from insurancedetail"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "insurancedetail")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
'insert close
End If
'myconnection close
End Sub
Way too many Class level variables. Especially not myconnection and cmd. What in the world is er? Procedures should not do too much. Move some code off to other procedures, especially if they will be called more than once.
For database objects use Using blocks. They will ensure that your objects are closed and disposed even if there is an error. You don't appear to be using the DataAdapter so just fill a DataTable directly. It can be bound to a DataGridView.
There is no reason to fill the DataTable again before the save. You may want to refill is again after the save.
I am guessing at the datatypes in your database. You must check the database to get the correct datatypes and for string types get the size of the field. Convert your TextBox values to the correct types. I have only used a few of your fields for demonstration purposes. Make sure you add your parameters in the same order that they appear in the sql statement.
Private dt As New DataTable
Private connString As String = "provider=microsoft.ace.oledb.12.0;data source=C:\Users\DELL\source\repos\HRIS SYSTEM\loginformdatabase\BLUESTREAM.accdb"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SetDatePickerValues()
FillDataTable()
End Sub
Private Sub Save_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Using cn As New OleDbConnection(connString)
Using cmd As New OleDbCommand("Insert Into insurancedetail(Name,EmployeeID,PAN) Values(#Name, #EmployeeID, #PAN);", cn)
cmd.Parameters.Add("#Name", OleDbType.VarChar, 100).Value = TextBox1.Text
cmd.Parameters.Add("#EmployeeID", OleDbType.Integer).Value = CInt(TextBox2.Text)
cmd.Parameters.Add("#PAN", OleDbType.VarChar, 100).Value = TextBox3.Text
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
FillDataTable()
Dim result As Integer = MessageBox.Show("New insurance detail Added. Want To Add Another One.", "Added", MessageBoxButtons.YesNo)
If result = DialogResult.No Then
Me.Close()
Else
ClearForm()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ClearForm()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
TextBox9.Clear()
TextBox10.Clear()
TextBox11.Clear()
TextBox12.Clear()
TextBox13.Clear()
TextBox14.Clear()
TextBox15.Clear()
TextBox16.Clear()
TextBox17.Clear()
TextBox18.Clear()
TextBox20.Clear()
ComboBox1.ResetText()
ComboBox2.ResetText()
ComboBox3.ResetText()
ComboBox4.ResetText()
ComboBox5.ResetText()
SetDatePickerValues()
End Sub
Private Sub FillDataTable()
Try
dt.Clear()
Using cn As New OleDbConnection(connString)
Using cmd As New OleDbCommand("Select * From insurancedetail", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub SetDatePickerValues()
DateTimePicker1.Value = DateTime.Now
DateTimePicker2.Value = DateTime.Now
DateTimePicker3.Value = DateTime.Now
End Sub

Register Form Issues VB.Net

I am having an issue when I am setting up this Register form.
My current code is this:
Public Class Form2
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim MyDocumentsFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim DBTest1 As String
Dim DBTestP1 As String
Dim cmd As New OleDbCommand(sql, con)
Dim connStr As String
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New OleDb.OleDbConnection(connStr)
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
TheDatabase = "\Robocopy_Test.accdb"
MyDocumentsFolder = "C:\Users\Dan\Desktop\WindowsApplication2"
FullDatabasePath = MyDocumentsFolder & TheDatabase
dbSource = "Data Source = C:\Users\Dan\Desktop\WindowsApplication2\Robocopy_Testaccdb1.accdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM Robocopy"
da = New OleDb.OleDbDataAdapter(sql, con)
'da.Fill(ds, "Robocopy")
MessageBox.Show("Databse is Open")
DBTest1 = DBTest.Text
DBTestP1 = DBTestP.Text
'DBTest.Text = ds.Tables("Robocopy").Rows(0).Item(1)
'DBTestP.Text = ds.Tables("Robocopy").Rows(0).Item(2
sql = "INSERT INTO Robocopy(username,password) VALUES('" & DBTest1 & "','" & DBTestP1 & "')"
cmd.Connection = connection
connection.Open()
cmd.CommandText = sql
da.InsertCommand = cmd
da.InsertCommand.ExecuteNonQuery()
connection.Close()
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Sub
Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
con.Close()
MessageBox.Show("Database Is now Closed")
End Sub
End Class
I am having the issue at connection.open(). The error that I am having is
The ConnectionString property has not been initialized.
I have been trying for the past hour to find different ways to write to the database but to no prevail and I cannot figure this out.
[In response to Steve
My code after editing and still the same error
Imports System.Data.OleDb
Public Class Form2
Dim connection As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim MyDocumentsFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim DBTest1 As String
Dim DBTestP1 As String
Dim cmd As New OleDbCommand(sql, connection)
Dim connStr As String
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New OleDb.OleDbConnection(connStr)
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
TheDatabase = "\Robocopy_Test.accdb"
MyDocumentsFolder = "C:\Users\Dan\Desktop\WindowsApplication2"
FullDatabasePath = MyDocumentsFolder & TheDatabase
dbSource = "Data Source = C:\Users\Dan\Desktop\WindowsApplication2\Robocopy_Testaccdb1.accdb"
Me.connection.ConnectionString = dbProvider & dbSource
Me.connection.Open()
sql = "SELECT * FROM Robocopy"
da = New OleDb.OleDbDataAdapter(sql, connection)
'da.Fill(ds, "Robocopy")
MessageBox.Show("Databse is Open")
DBTest1 = DBTest.Text
DBTestP1 = DBTestP.Text
'DBTest.Text = ds.Tables("Robocopy").Rows(0).Item(1)
'DBTestP.Text = ds.Tables("Robocopy").Rows(0).Item(2
sql = "INSERT INTO Robocopy(username,password) VALUES('" & DBTest1 & "','" & DBTestP1 & "')"
cmd.Connection = connection
connection.Open()
cmd.CommandText = sql
da.InsertCommand = cmd
da.InsertCommand.ExecuteNonQuery()
connection.Close()
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Sub
Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
connection.Close()
MessageBox.Show("Database Is now Closed")
End Sub
End Class
Global variables could be very ....evil. Expecially if you name them with the same name of a local variable.
Me.connection is not the same variable connection declared as local variable inside the sub. You set the connection string on the global variable then use the local variable without any connection string
Change these two lines
Me.connection.ConnectionString = dbProvider & dbSource
Me.connection.Open()
removing the Me.
connection.ConnectionString = dbProvider & dbSource
connection.Open()
and don't open the connection two times.
In any case, you don't need the adapter at all to execute an insert command
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source = C:\Users\Dan\Desktop\WindowsApplication2\Robocopy_Testaccdb1.accdb"
Dim connStr = dbProvider & dbSource
DBTest1 = DBTest.Text
DBTestP1 = DBTestP.Text
sql = "INSERT INTO Robocopy(username,[password]) VALUES('" & DBTest1 & "','" & DBTestP1 & "')"
Using connection = New OleDb.OleDbConnection(connStr)
Using cmd = new OleDb.OleDbCommand(sql, connection )
connection.Open()
cmd.ExecuteNonQuery()
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Using
End Using
End Sub
I see also that you have commented out the Parameterized approach to your query. Please do yourself a favour and restore as soon as possible the parameters logic. It is a lot more safe and avoids numerous errors
Finally Password is a reserved keyword in Access.Use square brakets around it otherwise you will see an unexplicable "Syntax Error" in your insert command

How to do a registerform by ASP.NET VB SQL

I am designing a registerform by vb.net but I don't know how to do this.
The following is my code:
Protected Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
Dim Conn As SqlConnection = New SqlConnection("localdb\v11.0")
Conn.Open()
Dim sqlstr As String = "insert into user_profile(username,password,nickname,realname,email) values('&username.Text&','&password.Text&','&nickname.Text&','&realname.Text&','&email.Text&')"
Dim cmd As New SqlCommand(sqlstr, Conn)
cmd.ExecuteNonQuery()
cmd.Cancel()
Conn.Close()
Conn.Dispose()
End Sub
but there is some errors...
and, is this concept right? If click the button then insert the data into SQL database?
Protected Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
Dim Conn As SqlConnection = New SqlConnection("localdb\v11.0")
Conn.Open()
Dim sqlstr As String = "insert into user_profile(username, password, nickname, realname, email) values('" & username.Text & "','" & password.Text & "','" & nickname.Text & "','" & realname.Text & "','" & email.Text &"')"
Dim cmd As New SqlCommand(sqlstr, Conn)
cmd.ExecuteNonQuery()
cmd.Cancel()
Conn.Close()
Conn.Dispose()
End Sub
You need to build your sqlstr correctly ... use quotes to separate the string from values of text boxes. You are also open to sql injections you should use paramaterised values.

The connection string property has not been initialized

I am trying to search my database using the below code, but I am getting the above error.
Private Sub ButtonSearch_Click(sender As System.Object, e As System.EventArgs) Handles ButtonSearch.Click
myConnection.Open()
Textlocation.Clear()
Dim str As String
str = "select * From STUDENTS where ADMINNO like " & "'%" & SearchTextBox.Text & "%'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
Textadminac.Text = dr("ADMINNO").ToString
End While
myConnection.Close()
End Sub

declare "data source" in a connection string as 'variable' in VB.NET

Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Dim bs As New BindingSource
m_DataAdapter = New OleDbDataAdapter("SELECT * FROM Table1 ORDER BY ID", "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=C:\Users\rebel23\Desktop\sampledata.mdb")
m_DataAdapter.Fill(m_DataSet)
bs.DataSource = m_DataSet.Tables(0)
BindingNavigator1.BindingSource = bs
txtAnimal.DataBindings.Add("Text", bs, "TextBox6.text")
txtSpecies.DataBindings.Add("Text", bs, "TextBox7.text")
In the above code i want to change the "data source" and declare it as TextBox1.text
So that the user will decide the data source at run time...
Also i want the same for 'Table1' and 'ID'
but how to do that??
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Dim bs As New BindingSource
Dim myTableName As String
Dim myOrderingColumn As String
Dim mybind1 As String
Dim mybind2 As String
myTableName = TextBox3.Text
myOrderingColumn = TextBox4.Text
mybind1 = TextBox6.Text
mybind2 = TextBox7.Text
m_DataAdapter = New OleDbDataAdapter("SELECT * FROM " & myTableName & " ORDER BY " & myOrderingColumn, "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & TextBox5.Text)
m_DataAdapter.Fill(m_DataSet)
bs.DataSource = m_DataSet.Tables(0)
BindingNavigator1.BindingSource = bs
txtAnimal.DataBindings.Add("Text", bs, "" & TextBox6.Text & "")
txtSpecies.DataBindings.Add("Text", bs, "" & TextBox7.Text & "")
End Sub
hey i got the code man !!!! its working .... thanks a lot for your support and suggestions #matzone
I did it in different way ..
Dim myConn = New OleDb.OleDbConnection( "Provider=Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\rebel23\Desktop\sampledata.mdb;Jet OLEDB:Database Password=mypass")
Dim cmd As OleDbCommand
Dim ds as DataSet = New DataSet
myConn.Open() '--> open conn
cmd = New OleDbCommand("SELECT * FROM Table1 ORDER BY ID", myConn)
cmd.Fill(ds, "predator") ' ---> named dataset as Predator
txtAnimal.DataBindings.Add("Text", ds.Tables("predator"), "'" & TextBox6.text & "'")
txtSpecies.DataBindings.Add("Text",ds.Tables("predator"), "'" & TextBox7.text & "'")
' ....
' .....
cmd.Dispose()
ds.Dispose()
cnn.Close()