Syntax error (missing operator) in query expression 'Prod_Num =' - vb.net

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.

Related

an error when choosing between two specific date in datagridview in VISUAL BASIC

i wrote a code for searching between two specific date in Visual Basic and it was run correctly.
but now there's a problem.
- when i chose between two date in DECEMBER that i inserted a data in, it show correctly.
-- but when i chose two date in month before that doesn't have any data it show the DECEMBER data.
-- also when i chose a date in DECEMBER and the another in JANUARY there's no data!
i use MS Access for my data base -
here is my code...
Imports System.Data.OleDb
Imports System.Data.DataTable
Public Class p2
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\sh\Desktop\FP\Fproject.accdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Dim Str As String
Public dr As OleDbDataReader
Private Sub p2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
MyConn.Open()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Str = "SELECT * FROM att WHERE (date1 between '" & Me.DateTimePicker1.Value.ToShortDateString & "' and '" & Me.DateTimePicker2.Value.ToShortDateString & "')"
Dim cmd As OleDbCommand = New OleDbCommand(Str, MyConn)
dr = cmd.ExecuteReader
While dr.Read()
If dr.HasRows Then
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select id1 from [att] where (date1 >= '" & Me.DateTimePicker1.Value.ToShortDateString & "' and date1 <= '" & Me.DateTimePicker2.Value.ToShortDateString & "')", MyConn)
da.Fill(ds, "att")
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
Return
End If
End While
MsgBox("no data for this chosen date", MsgBoxStyle.Exclamation, "Warning")
DateTimePicker1.Value = Now
Return
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
FirstForm.Show()
Me.Hide()
End Sub
End Class

VB.Net OleDBConnection code to update access database from DataGridView

I have a simple userform with a DataGridView and I would like to use OleDB code to update the accdb database based on any entries made in the gridview. The load button works fine, but the save button produces this error:
Update requires a valid UpdateCommand when passed DataRow collection with modified rows.
Here is my code:
Imports System.Data.OleDb
Public Class Form1
Dim myConString As String
Dim con As OleDbConnection = New OleDbConnection
Dim Dadapter As OleDbDataAdapter
Dim DSet As DataSet
Dim DSet2 As DataSet
Dim ConCMD As OleDb.OleDbCommand
Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
myConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\Psmccsfs01\snd\PRODUCTION\Licensed\Reporting\FTO Adjustment Tools\FTO_Log_DB.accdb;"
con.ConnectionString = myConString
con.Open()
Dadapter = New OleDbDataAdapter("select * from FTO_Log", con)
DSet = New DataSet
Dadapter.Fill(DSet, "FTO_Log")
DataGridView1.DataSource = DSet.Tables("FTO_Log")
con.Close()
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
Using con = New OleDbConnection(myConString)
con.Open()
Dadapter.Update(DSet, "FTO_Log")
End Using
End Sub
End Class
dataAdpater.UpdateCommand = new SqlCommand(
"UPDATE Categories SET CategoryName = #CategoryName " +
"WHERE CategoryID = #CategoryID", connection);
notice the typo in the code above, straight from the msdn site ;p
short and simple: http://msdn.microsoft.com/en-us/library/33y2221y%28v=vs.110%29.aspx

Syntax error in INSERT into statement when adding to access database

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

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.

I am getting an error "Syntax error in Update statement" from code below:

I am getting an error "Syntax error in Update statement" from code below:
Public Class Emp
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
Dim inc As Integer
Dim MaxRows As Integer
Private Sub Emp_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dbProvider = "Provider=Microsoft.Ace.OLEDB.12.0;"
dbSource = "Data Source = C:\Users\Blessing\Documents\IBCARIP.accdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * From Employees"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "IBCARIP")
'con.Close()
txtID.Text = ds.Tables("IBCARIP").Rows(0).Item(0)
txtName.Text = ds.Tables("IBCARIP").Rows(0).Item(1)
MaxRows = ds.Tables("IBCARIP").Rows.Count
inc = -1
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If InputBox("Please enter Clearance Level 1 Code", ) <> "me" Then
MsgBox("Invalid clearence code entered. Please make sure you have enough previlegies to perfom this operation..!", MsgBoxStyle.OkOnly)
Else
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("IBCARIP").Rows(inc).Item(0) = txtID.Text
ds.Tables("IBCARIP").Rows(inc).Item(1) = txtName.Text
da.Update(ds, "IBCARIP") <<<<<<<<<<<<<<<<<<<<<<<<<<<<SYNTAX ERROR IN UPDATE STATEMENT
End If
End Sub
Can someone please help