Syntax error in INSERT into statement when adding to access database - vb.net

Someone please help me on finding the error on my code.
the error is at the line inside my try and catch where im trying to add record on my database Access. the error is "Syntax error in INSERT into statement". I already tried using
ds.Tables("Users").Rows.Add(dsNewRow)
da.Update(ds, "Users")
on my registration for voters and it works fine. idk why it doesnt work on this form (user registration).
Imports System.Data.OleDb
Public Class UserRegister
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim da As New OleDb.OleDbDataAdapter
Dim sql As String
Private Sub Label4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label4.Click
End Sub
Private Sub UserRegister_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dbProvider = " PROVIDER=Microsoft.jet.OLEDB.4.0;"
dbSource = "Data Source= C:\Users\Ronel\Documents\database\CSdatabase.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT*FROM tblUsers"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Users")
MsgBox("Database now Open")
con.Close()
'MsgBox("Database now Close")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
Dim empty =
Me.Controls.OfType(Of TextBox)().Where(Function(txt) txt.Text.Length = 0)
If empty.Any Then
MessageBox.Show(String.Format("PLEASE FILL ALL FIELDS:"))
Else
dsNewRow = ds.Tables("Users").NewRow()
dsNewRow.Item("Username") = TextBoxUser.Text
dsNewRow.Item("Password") = TextBoxPass.Text
dsNewRow.Item("LastName") = TextBoxFN.Text
dsNewRow.Item("GivenName") = TextBoxGN.Text
dsNewRow.Item("MiddleName") = TextBoxMN.Text
' Try
ds.Tables("Users").Rows.Add(dsNewRow)
da.Update(ds, "Users")
' Catch ex As Exception
MsgBox("Error updating")
' End Try
' Me.Dispose()
'Comelec.Show()
End If
End Sub
End Class

I see a few problems. First, your SQL statement needs some spaces in it. Instead of sql = "SELECT*FROM tblUsers", use sql = "SELECT * FROM tblUsers".
Second, when using OleDbCommandBuilder, the code connects to the database using the SELECT statement you provided for the DataAdapter, and uses that to generate the necessary SQL for Update, Delete, and Insert statements. The connection to the database needs to be open for this to occur -- you connection is closed at the point where the CommandBuilder is running. This is probably where the syntax error is coming from.
The CommandBuilder will create these statements using all of the fields specified in the SELECT. If you have fields in your Users table other than the five you are attempting to populate, the OleDbCommandBuilder is still going to build an INSERT statement that will attempt to fill those fields as well. Depending on how your table is structured, this may cause rows to be rejected if required fields aren't populated. To take a look at what SQL statements are being generated, you can look at properties of the DataAdapter object after using the CommandBuilder:
con.Open
sql = "SELECT * FROM tblUsers"
da = New OleDb.OleDbDataAdapter(sql, con)
Dim cb As New OleDb.OleDbCommandBuilder(da)
Debug.Print("SELECT: " & da.SelectCommand.CommandText)
Debug.Print("UPDATE: " & da.UpdateCommand.CommandText)
Debug.Print("DELETE: " & da.DeleteCommand.CommandText)
Debug.Print("INSERT: " & da.InsertCommand.CommandText)
Some additional reading on CommandBuilders is available here: http://msdn.microsoft.com/en-us/library/tf579hcz%28v=vs.110%29.aspx
Give this a try:
Imports System.Data.OleDb
Public Class UserRegister
Const dbProvider As String = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
Dim dbSource As String = "Data Source=C:\Users\Ronel\Documents\database\CSdatabase.mdb"
Dim con As New OleDb.OleDbConnection(dbProvider & dbSource)
Dim ds As New DataSet
Dim da As New OleDb.OleDbDataAdapter
'Specify only the fields you need
Dim sql As String = "SELECT UserName, Password, LastName, GivenName, MiddleName FROM tblUsers"
Private Sub UserRegister_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.Open()
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Users")
' Get commands now, while connection is open. Do this once when the form is loaded, not every time button is clicked.
Dim cb As New OleDb.OleDbCommandBuilder(da)
con.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Validation code goes here
If empty.Any Then
MessageBox.Show(String.Format("PLEASE FILL ALL FIELDS:"))
Else
Dim dsNewRow As DataRow
dsNewRow = ds.Tables("Users").NewRow()
dsNewRow.Item("Username") = TextBoxUser.Text
dsNewRow.Item("Password") = TextBoxPass.Text
dsNewRow.Item("LastName") = TextBoxFN.Text
dsNewRow.Item("GivenName") = TextBoxGN.Text
dsNewRow.Item("MiddleName") = TextBoxMN.Text
Try
con.Open()
ds.Tables("Users").Rows.Add(dsNewRow)
da.Update(ds, "Users")
Catch ex As Exception
MsgBox("Error updating: " & Err.Description)
Finally
con.Close()
End Try
End If
End Sub
End Class

Related

Adapter update statement in oledb

I have a form with retrieved data form ms access database. While updating using the adapter update statement, it shows Syntax error.
The following are the connection code in form load event and update button click event.
could you please let me know whats wrong in this?
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\DESKTOP\VBATESTING\ADPE Project\Project Tables\ADPE_Table.accdb"
inc = 0
Dim Con As New OleDbConnection()
Dim Cmd As New OleDbCommand
Dim SQL As String = "SELECT * FROM Heidelberg"
Con.ConnectionString = strConn
Try
Con.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Cmd = New OleDbCommand(SQL, Con)
Adapter.SelectCommand = New OleDbCommand(SQL, Con)
ds = New DataSet
Adapter.Fill(ds, "testing")
MaxRows = ds.Tables("testing").Rows.Count
Label1.Text = "Total Records :" & MaxRows
NavigateRecords()
End Sub
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
Dim cb As New OleDb.OleDbCommandBuilder(Adapter)
ds.Tables("testing").Rows(inc).Item(5) = TextBox1.Text
ds.Tables("testing").Rows(inc).Item(2) = TextBox2.Text
ds.Tables("testing").Rows(inc).Item(3) = TextBox3.Text
ds.Tables("testing").Rows(inc).Item(4) = TextBox4.Text
Try
Adapter.Update(ds, "testing")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
You have way too many commands in your Form.Load.
One
Dim Cmd As New OleDbCommand
Two
Cmd = New OleDbCommand(SQL, Con)
Three
Adapter.SelectCommand = New OleDbCommand(SQL, Con)
Every time you use the New keyword, you create another command.
If you are only dealing with a single table, you don't need a DataSet. The extra object adds extra weight and complicates the code a bit.
Private inc As Integer
Private Adapter As New OleDbDataAdapter
Private MaxRows As Integer
Private dat As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\DESKTOP\VBATESTING\ADPE Project\Project Tables\ADPE_Table.accdb"
inc = 0
Using Con As New OleDbConnection(strConn)
Using Cmd As New OleDbCommand("SELECT * FROM Heidelberg;", Con)
Adapter.SelectCommand = Cmd
Try
Adapter.Fill(dat)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Using
MaxRows = dat.Rows.Count
Label1.Text = "Total Records :" & MaxRows
NavigateRecords()
End Sub
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
dat.Rows(inc).Item(5) = TextBox1.Text
dat.Rows(inc).Item(2) = TextBox2.Text
dat.Rows(inc).Item(3) = TextBox3.Text
dat.Rows(inc).Item(4) = TextBox4.Text
Dim cb As New OleDbCommandBuilder(Adapter)
'This will take care of any spaces that you have in column names.
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
Try
Adapter.Update(dat)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Displaying Data from SQL in TextBox by clicking ComboBox item in Visual Basic 2012

I have three columns in SQL, which I want the data displayed in three textboxes by clicking an item in ComboBox.
The issue is not really displaying. I can save the data fine and display. However, one of the text fields will only show one cell and not update when a different item is selected. Hope this is making sense.
Here is the code I have for saving:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myconnect As New SqlClient.SqlConnection
myconnect.ConnectionString = "Data Source=.\INFLOWSQL;Initial Catalog=RioDiary;Integrated Security=True"
Dim mycommand As SqlClient.SqlCommand = New SqlClient.SqlCommand()
mycommand.Connection = myconnect
mycommand.CommandText = "INSERT INTO MyDiary (Title, DiaryContent, DiaryDate) VALUES (#Title, #DiaryContent, #DiaryDate)"
myconnect.Open()
Try
mycommand.Parameters.Add("#Title", SqlDbType.VarChar).Value = TextBox1.Text
mycommand.Parameters.Add("#DiaryContent", SqlDbType.VarChar).Value = TextBox2.Text
mycommand.Parameters.Add("#DiaryDate", SqlDbType.VarChar).Value = TextBox3.Text
mycommand.ExecuteNonQuery()
MsgBox("Success")
Catch ex As System.Data.SqlClient.SqlException
And here is the code for displaying in form1:
Imports System.Data.SqlClient
Public Class Form1
Dim con As New SqlConnection
Dim ds As New DataSet
Dim da As New SqlDataAdapter
Dim sql As String
Dim inc As Integer
Dim MaxRows As Integer
Dim max As String
Dim dt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'RioDiaryDataSet5.MyDiary' table. You can move, or remove it, as needed.
Me.MyDiaryTableAdapter.Fill(Me.RioDiaryDataSet5.MyDiary)
Dim con As New SqlConnection(" Data Source=.\INFLOWSQL;Initial Catalog=RioDiary;Integrated Security=True")
Dim cmd As New SqlCommand("Select Title,DiaryContent,DiaryDate FROM MyDiary ")
Dim da As New SqlDataAdapter
da.SelectCommand = cmd
cmd.Connection = con
da.Fill(ds, "MyDiary")
con.Open()
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.DisplayMember = "Title'"
ComboBox1.ValueMember = "DiaryContent"
End Sub
Private Sub NewEntryToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewEntryToolStripMenuItem.Click
AddEntry.Show()
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If (Not Me.ComboBox1.SelectedValue Is Nothing) Then
Me.TextBox2.Text = ComboBox1.Text
Me.TextBox3.Text = ComboBox1.SelectedValue.ToString
End If
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If dt.Rows.Count > 0 Then
TextBox1.Text = dt.Rows(0)("DiaryDate").ToString() 'Where ColumnName is the Field from the DB that you want to display
End If
End Sub
End Class
As you can see from the code, I want to display Title and DiaryContent in two separate textboxes by clicking on Title in the Combobox. This works fine.
The issue I have is DiaryDate only shows the first entry and does not update when selecting the Item from ComboBox.
Can anyone help?
You can try to play with ComboBox's SelectedItem property. Since ComboBox's DataSource is DataTable here, SelectedItem of ComboBox represent a row in DataTable. Given DataRow in hand, you can display value of any column of DataRow in TextBoxes :
........
If (Not Me.ComboBox1.SelectedItem Is Nothing) Then
Dim SelectedItem = TryCast(comboBox1.SelectedItem, DataRowView)
Me.TextBox1.Text = SelectedItem.Row("Title").ToString()
Me.TextBox2.Text = SelectedItem.Row("DiaryContent").ToString()
Me.TextBox3.Text = SelectedItem.Row("DiaryDate").ToString()
End If
........
Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim cn As New SqlClient.SqlConnection("Data Source=thee-pc;Initial Catalog=jobportal;Integrated Security=True")
Dim cmd As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim da As New SqlClient.SqlDataAdapter
Dim reader As SqlClient.SqlDataReader
Try
cn.Open()
Dim sql As String
sql = "select * from Register"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
While reader.Read
Dim id = reader.Item("cid")
ComboBox1.Items.Add(id)
End While
cn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim cn As New SqlClient.SqlConnection("Data Source=thee-pc;Initial Catalog=jobportal;Integrated Security=True")
Dim cmd As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim da As New SqlClient.SqlDataAdapter
Dim reader As SqlClient.SqlDataReader
Try
cn.Open()
Dim sql As String
sql = "select * from register where cid ='" + ComboBox1.Text + "'"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
While reader.Read
TextBox1.Text = reader.Item("cname")
TextBox2.Text = reader.Item("dob")
End While
cn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Syntax error in INSERT INTO statement generated by OleDbCommandBuilder

Why does this keep telling me
Syntax error in INSERT INTO statement
I searched for more details but it keeps telling me this.
This is the code :
Imports System.Data
Imports System.Data.OleDb
Public Class f9
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim sql As String
Private Sub f9_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dbProvider = "Provider=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = E:\21.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM snack"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "snack")
da = New OleDb.OleDbDataAdapter(sql, con)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles b1.Click
Me.Close()
x = x + (5 * 1)
If d.tc.Text = f7.b1.Text Then
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
dsNewRow = ds.Tables("snack").NewRow()
dsNewRow.Item("Date") = f1.d1.Text
dsNewRow.Item("Order") = d.tc.Text
dsNewRow.Item("Number Of Items") = b1.Text
dsNewRow.Item("Price") = " 5 "
dsNewRow.Item("Total") = x
ds.Tables("snack").Rows.Add(dsNewRow)
da.Update(ds, "snack")
con.Close()
End If
End Sub
End Class
Some of your field names are reserved words in Access SQL (Date, Order) and you also have a field name with spaces in it. The default configuration of the CommandBuilder will not produce valid SQL statements in cases like this.
To fix this issue, immediately after the line...
Dim cb As New OleDb.OleDbCommandBuilder(da)
...add the following two lines:
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
That will tell the command builder to enclose table and field names in square brackets ([]) so instead of generating a statement like
INSERT INTO snack (Date, Order, Number Of Items) VALUES ...
it will generate a statement like
INSERT INTO [snack] ([Date], [Order], [Number Of Items]) VALUES ...
Those square brackets are required for the SQL statement to be syntactically correct.

Syntax error (missing operator) in query expression 'Prod_Num ='

This Syntax error (missing operator) in query expression 'Prod_Num ='. always shows up when I'm trying to search an item in the database. Please help me.
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim cmd As OleDbCommand
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
Dim sql As String
Dim dbp As String
Dim dbs As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dbp = "Provider = Microsoft.ACE.OLEDB.12.0;"
dbs = "Data Source=" & Application.StartupPath & "/POS.accdb"
con.ConnectionString = dbp & dbs
con.ConnectionString = dbp & dbs
con.Open()
sql = "SELECT * FROM tblInventory"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(dt)
dgList.DataSource = dt
txtPNum.Focus()
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
dt.Clear()
txtPNum.Text = ""
sql = "SELECT * FROM tblInventory WHERE Prod_Num =" & txtPNum.Text
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(dt)
dgList.DataSource = dt
txtPName = dt.Rows(0).Item(1)
txtNOrder = dt.Rows(0).Item(2)
txtPRem = dt.Rows(0).Item(3)
txtPrice = dt.Rows(0).Item(4)
txtPNum.Focus()
End Sub
My guess is that you have problem here:
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
dt.Clear()
txtPNum.Text = "" ' <-----------------
sql = "SELECT * FROM tblInventory WHERE Prod_Num =" & txtPNum.Text
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(dt)
dgList.DataSource = dt
txtPName = dt.Rows(0).Item(1)
txtNOrder = dt.Rows(0).Item(2)
txtPRem = dt.Rows(0).Item(3)
txtPrice = dt.Rows(0).Item(4)
txtPNum.Focus()
End Sub
Remove this line:
txtPNum.Text = ""
Since you always clears the txtPNum textbox's text before passing it to the query.
NOTE:
Don't forget to implement it via parameterized query. This is not a good approach.
See parameterized query examples:
Example 1
Example 2
Hope it helps!
does txtPNum.Text contain any data?
Why don't you try checking that, because if it is empty your running SQL statement is "SELECT * FROM tblInventory WHERE Prod_Num =" which would raise that error.
Also if the Prod_Num column is integer, perhaps you should use int(txtPNum.Text) if that value is a string, this would also prevent SQL Injection.
In addition to the problem with txtPNum.Text that others have pointed out, I would recommend a couple of other things:
Use parameterized queries to avoid SQL Injection.
Use Using blocks with your connection, and close the connection as soon as you are done. In your Form_Load, for example, you open the connection and leave it open. That is not good practice.
Example:
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Dim con As OleDbConnection
Dim cmd As OleDbCommand
Dim da As OleDbDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
Dim dbp As String
Dim dbs As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dbp = "Provider = Microsoft.ACE.OLEDB.12.0;"
dbs = "Data Source=" & Application.StartupPath & "/POS.accdb"
Using con As OleDbConnection = New OleDbConnection(dbp & dbs)
con.Open()
da = New OleDbDataAdapter("SELECT * FROM tblInventory", con)
da.Fill(dt)
dgList.DataSource = dt
End Using
txtPNum.Focus()
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
dt.Clear()
Using con As OleDbConnection = New OleDbConnection(dbp & dbs)
con.Open()
da = New OleDbDataAdapter("SELECT * FROM tblInventory WHERE Prod_Num = #ProdNum", con)
da.SelectCommand.Parameters.AddWithValue("#ProdNum", txtPNum.Text)
da.Fill(dt)
dgList.DataSource = dt
End Using
txtPName = dt.Rows(0).Item(1)
txtNOrder = dt.Rows(0).Item(2)
txtPRem = dt.Rows(0).Item(3)
txtPrice = dt.Rows(0).Item(4)
txtPNum.Focus()
End Sub
I would also recommend adding some Try Catch blocks to handle errors, and you may need to convert the values you're assigning to text boxes if they're something other than String.

Vb.Net: How to execute SQL query inisde datagrid?

I have load a csv file using the code below
Dim fi
Dim conn
Dim adapter1 As New OleDbDataAdapter
Dim ds As New DataSet
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
fi = New FileInfo("C:\path\Book1.csv")
conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName)
conn.Open()
adapter1.SelectCommand = New OleDbCommand("SELECT * FROM " & fi.Name, conn)
adapter1.Fill(ds, "DATA")
DataGridView1.DataSource = ds.Tables(0).DefaultView
End Sub
Now, I want to execute a SQL query like create, select, update, etc inside the gridview. For example, I want to create a new column "test" and fill that column with the values from column "a" and "b". But I get error. Can you please correct the code?
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Try
DataGridView2.Columns.Add("test", "test")
adapter1.SelectCommand = New OleDbCommand("Update Datagridview1 SET test = a + b", conn)
Dim dsA As New DataSet
adapter1.Fill(dsA, "DATA")
DataGridView2.DataSource = dsA.Tables(0).DefaultView
Catch exp As Exception
MsgBox("Error : " & exp.Message)
End Try
End Sub
I cannot test this code now, but usually you change the schema of the DataTable linked to the DataGridView to reflect the new column, and, in your specific case set the Expression property of the newly created column
Dim dv As DataView = CType(DataGridView2.DataSource, DataView)
Dim dc = dv.Table.Columns.Add("test", System.Type.GetType("System.String"))
dc.Expression = "[A] + [B]"
This strongly depends on the datatype of the columns A and B. Here I suppose that they are both strings