Data type mismatch in criteria expression (vb.net, access) - vb.net

I am trying to take data from the database to the grid. The condition is SELECT * FROM entries WHERE edate='" & Me.dtpDate.Value.Date & "'" But I am getting the error message Data type mismatch in criteria expression. Please see the code below. Also I have attached a screenshot of the error message.
Private Sub dtpDate_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles dtpDate.Leave
'GetDayBookOpeningBalance()
If Me.lblHeading1.Text <> "Daybook entry" Then
Using MyConnection As OleDb.OleDbConnection = FrmCommonCodes.GetConnection(),
MyAdapter As New OleDb.OleDbDataAdapter("SELECT * FROM entries WHERE edate='" & Me.dtpDate.Value.Date & "'", MyConnection)
'Format(Me.dtpDate.Value.Date, "dd/MM/yyyy"))
If MyConnection.State = ConnectionState.Closed Then MyConnection.Open()
Using MyDataSet As New DataSet
MyAdapter.Fill(MyDataSet, "entries")
Me.grdDayBook.DataSource = MyDataSet.Tables("entries")
Dim DataSetRowCount As Integer = MyDataSet.Tables("entries").Rows.Count
If DataSetRowCount > 0 Then
SetGridProperty()
Else
ShowBlankGrid()
FrmCommonCodes.MessageDataNotFound()
End If
End Using
End Using
Else
ShowBlankGrid()
End If
End Sub

This is exactly what could happen for not using parameterized queries.
I bet that your column edate is a column of type Date/Time but you concatenate your Me.dtpDate.Value.Date to the remainder of your sql string command.
This forces an automatic conversion from DateTime to String but the conversion is not as your database would like to see.
If you use a parameter there is no conversion and the database engine understand exactly what you are passing.
Dim sqlText = "SELECT * FROM entries WHERE edate=#dt"
MyAdapter As New OleDb.OleDbDataAdapter(sqlText, MyConnection)
MyAdapter.SelectCommand.Parameters.Add("#dt", OleDbType.Date).Value = Me.dtpDate.Value.Date
....

Related

How do I change data type to fix data type mismatch in criteria expression

I'm trying to get the database value of an item that i put on a listbox to display to the textbox. (vb.net)
My database table name is 'productlog', in this table has 3 columns, productid, productname, and price. I got the productname to display on a listbox that I made, now I am attempting to display the 3 columns on 3 textboxes. However, I get the "data type mismatch in criteria expression" error on my ExecuteReader line. Here's my code:
Public Class shop
Dim provider As String
Dim datafile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Private Sub listboxitems_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listboxitems.SelectedIndexChanged
Dim lbconn As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.Oledb.12.0; Data Source = C:\Users\USER PC\Desktop\orderDB1.accdb")
Dim lbcmd As New OleDb.OleDbCommand("SELECT productid, product, price FROM productlog WHERE productid =' & listboxitems.Text & ' AND product ='" & listboxitems.Text & "' AND price =' & listboxitems.Text & '", lbconn)
Dim lbreader As OleDbDataReader
lbconn.Open()
lbreader = lbcmd.ExecuteReader() 'error appearing right here'
While lbreader.Read
txtproductid.Text = lbreader.GetInt32("productid")
txtproduct.Text = lbreader.GetString("product")
txtprice.Text = lbreader.GetInt32("price")
End While
lbconn.Close()
End Sub
Based on the other questions that I looked up, it might be because that 'productid' and 'price' are both integers and what I'm doing is for a String. I tried to remove the double quotes ('"& txtproductid.Text"') and turn them into 'txtproductid.Text', based from another question I looked up. The another answer that I saw was to convert the string into an integer - 'lbcmd.Parameters.AddwithValue("#productid", ConvertInt32("txtproductid.Text"))' not sure if that's correct but I ended up getting the same error. How do I work around this error? Thanks.
UPDATED CODE:
Private Sub listboxitems_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listboxitems.SelectedIndexChanged
Using lbconn As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.Oledb.12.0; Data Source = C:\Users\USER PC\Desktop\orderDB1.accdb")
Using lbcmd As New OleDb.OleDbCommand("SELECT productid, product, price FROM productlog WHERE productid = ? AND product = ? AND price = ?", lbconn)
'Set your values here. The parameters must be added in the same order that they
'appear in the sql SELECT command
Dim prodidparam As New OleDbParameter("#productid", Me.txtproductid.Text)
Dim prodparam As New OleDbParameter("#product", Me.txtproduct.Text)
Dim priceparam As New OleDbParameter("#price", Me.txtprice.Text)
lbcmd.Parameters.Add(prodidparam)
lbcmd.Parameters.Add(prodparam)
lbcmd.Parameters.Add(priceparam)
'Open the connection
lbconn.Open()
Using lbreader As OleDbDataReader = lbcmd.ExecuteReader()
While lbreader.Read
txtproductid.Text = lbreader.GetInt32("productid").ToString()
txtproduct.Text = lbreader.GetString("product")
txtprice.Text = lbreader.GetInt32("price").ToString()
End While
End Using
End Using
End Using
End Sub
You should not use string concatenation to create your SQL query as you are doing here. That opens you up to a sql injection hack. Instead you should use a parameterized query.
Try something like this (not tested):
Using lbconn As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.Oledb.12.0; Data Source = C:\Users\USER PC\Desktop\orderDB1.accdb")
Using lbcmd As New OleDb.OleDbCommand("SELECT productid, product, price FROM productlog WHERE productid = ? AND product = ? AND price = ?", lbconn)
'Set your values here. The parameters must be added in the same order that they
'appear in the sql SELECT command
lbcmd.Parameters.Add("productid", OleDb.OleDbType.Integer).Value = 1234
lbcmd.Parameters.Add("product", OleDb.OleDbType.VarChar).Value = "value of product"
lbcmd.Parameters.Add("price", OleDb.OleDbType.Integer).Value = 999
'Open the connection
lbconn.Open()
Using lbreader As OleDbDataReader = lbcmd.ExecuteReader()
While lbreader.Read
txtproductid.Text = lbreader.GetInt32("productid").ToString()
txtproduct.Text = lbreader.GetString("product")
txtprice.Text = lbreader.GetInt32("price").ToString()
End While
End Using
End Using
End Using
Since your code is using OleDbConnection you can't use named parameters. Note the question marks in the SELECT statement which server as placeholders for the values.
Note that when using OleDb, you have to add the parameters in the same order as they appear in your sql query.
The Using ... End Using statements ensure that the connection, command and datareader are disposed properly.

Error on Search Button

I searched on some codes on how to do a Search Button in VB.net. But somehow, it won't work because of an error. And simply because, I cannot understand its algorithm and function. Newbie here. Anyway, here is the code for the search button:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
myConnection.Open()
crd.Clear()
fn.Clear()
ln.Clear()
Dim str As String
str = "SELECT * FROM tblReg WHERE (Code = '" & src.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
crd.Text = dr("crd").ToString
fn.Text = dr("fName").ToString
ln.Text = dr("lName").ToString
End While
myConnection.Close()
End Sub
And the error was on:
dr = cmd.ExecuteReader
And VB said:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: No value given for one or more required parameters.
One should not follow online tutorials that teach very bad code. That code is very bad because it contains SQL injection and leaves database objects opened.
You should rewrite your code as follows:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
myConnection.Open()
crd.Clear()
fn.Clear()
ln.Clear()
Using cmd = New OleDbCommand("SELECT * FROM tblReg WHERE Code = ?", myConnection)
cmd.CommandType = CommandType.Text
With cmd.Parameters.Add(Nothing, OleDbType.VarChar, 50)
.Direction = ParameterDirection.Input
.Value = src.Text
End With
Using dr = cmd.ExecuteReader()
While dr.Read()
crd.Text = dr("crd").ToString
fn.Text = dr("fName").ToString
ln.Text = dr("lName").ToString
End While
End Using
End Using
myConnection.Close()
End Sub
You have to use question marks in place of parameters because you are using OleDbCommand that does not support named parameters.
Change OleDbType.VarChar to your actual column type.
Is this the link where you get the code?
http://www.visual-basic-tutorials.com/ReadFromAccess.htm
Kindly do not get the code read each data on the output shows and also check this part of the code.
crd.Text = dr("crd").ToString
fn.Text = dr("fName").ToString
ln.Text = dr("lName").ToString
are you sure crd,fname,lname are the name of your fields in your table? pls check it and also what is the field type of code? is it a text or INT that is Auto Increment? or just an INT? no matter what it is change your code.
from
str = "SELECT * FROM tblReg WHERE (Code = '" & src.Text & "')"
to
str = "SELECT * FROM tblReg WHERE Code =" & src.Text
Updated
I suggest better read or follow the whole instruction based on link where you get your code. I suggest do the same as what the link said create the same and when the program runs with no error then incorporate it with your program beacuse I tried it using VB.NET and Access and it worked Im sure you dont read it. Do this and Im sure you will not just get the code you need you will also learn.

Data type mismatch in criteria expression Error in VB.NET

Hi I am getting the above error in VB when attempting the following code, I have 3 text boxes on a form, after the user inputs a stock code I want the form to input the matching product group and product description in the relating text boxes. The code I am using is as follows
Private Sub txt_productcode_Leave(sender As Object, e As EventArgs) Handles txt_productcode.Leave
Dim dt As New DataTable
Dim connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:database
Dim SqlString As String = "select [product group],[product description] from [stock] where [stock code] = " & txt_productcode.Text & ""
Using conn As New OleDbConnection(connstring)
Using command As New OleDbCommand(SqlString, conn)
Using adapter As New OleDbDataAdapter(command)
conn.Open()
adapter.Fill(dt)
conn.Close()
End Using
Dim MyDataRow As DataRow = dt.Rows(0)
Dim x As Integer
x = dt.Rows.Count
For y = 0 To x - 1
If y < x Then
MyDataRow = dt.Rows(y)
txt_productgroup.Text = MyDataRow("product group")
txt_productdescription = MyDataRow("product description")
End If
Next
End Using
End Using
End Sub
Each time I attempt to run this the form crashes, I get the above error message and the following line is highlighted in the code
adapter.Fill(dt)
Can anyone please explain why this is not working? Thanks
First thing to do is to remove the string concatenation when you build the command text and use a parameter, then you set a TextBox for the description instead of its text property. Removed also some useless code
Private Sub txt_productcode_Leave(sender As Object, e As EventArgs) Handles txt_productcode.Leave
Dim dt As New DataTable
Dim connstring As String = "...."
Dim SqlString As String = "select [product group],[product description] " & _
"from [stock] where [stock code] = #stock"
Using conn As New OleDbConnection(connstring)
Using command As New OleDbCommand(SqlString, conn)
Using adapter As New OleDbDataAdapter(command)
conn.Open()
command.Parameters.AddWithValue("#stock", txt_productcode.Text)
adapter.Fill(dt)
End Using
For y = 0 To dt.Rows.Count - 1
Dim MyDataRow = dt.Rows(y)
txt_productgroup.Text = MyDataRow("product group").ToString()
txt_productdescription.Text = MyDataRow("product description").ToString()
Next
End Using
End Using
End Sub
Well, it's likely that your SQL statement contains an error. Perhaps you're missing quote characters in the WHERE condition:
"… WHERE [stock code] = '" + ... + "'"
' ^ ^
Btw. your code is prone to SQL injection attacks, due to building the SQL command using simple string concatenation instead of using a parameterized query.

Updating database with BindingSource data

This is my first post in here, but this forum already helped me a lot.
First, sorry for my English, i'm from Brazil and i'm trying to write without a translator.
I'm developing a software for a supermarket, but i'm having problems with the connection to the database. I'm trying to make all the connections and transactions programmatically (DataSets, BindingSources and so).
I've already managed to connect with SQL Server Express 2008, using a Function ("consulta") inside a Module ("db"):
Dim ad As SqlDataAdapter = New SqlDataAdapter
Function consulta(ByVal tabela As String, Optional opt As Boolean = False, Optional optparam As String = "") As DataSet
Dim ds As New DataSet
Try
Dim connstring As String = "Data Source=NOTEBOOK\SQLEXPRESS;Initial Catalog=SysMarket;Persist Security Info=True;User ID=admin;Password=XXXXXX"
Dim conObj As New SqlConnection(connstring)
Dim sql As String
If opt = True Then
sql = "SELECT * FROM " & tabela & " " & optparam
Else
sql = "SELECT * FROM " & tabela
End If
Dim cmd As SqlCommand = New SqlCommand(sql, conObj)
ad.SelectCommand = cmd
conObj.Open()
ad.Fill(ds, tabela)
ad.Dispose()
cmd.Dispose()
conObj.Close()
Return ds
Catch ex As Exception
MessageBox.Show("Erro na consulta" & vbCrLf & ex.InnerException.ToString, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
ds.Clear()
Return ds
End Try
End Function
And this is a part of the main code where I make a SelectQuery and put into a BindingSource:
Dim ds As DataSet = db.consulta("departamentos")
Private Sub cad_departamento_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BindingSource1.DataSource = ds
BindingSource1.DataMember = "departamentos"
TextBox1.DataBindings.Add("Text", BindingSource1, "id")
TextBox2.DataBindings.Add("Text", BindingSource1, "departamento")
End Sub
But my problem is when I have to Update the database, by adding, editing or deleting some item from BindingSource. Because in the Module I've closed the connection to the SQL Server. So I will need reopen this connection and then, somehow "read" the DataSet with the change and Update the database?
Someone could explain this to me or show me a example?
Thank you.
You will use a data adapter to save the data, just as you used one to retrieve the data. You will have to create an InsertCommand if you want to insert new records, an UpdateCommand if you want to update existing records and a DeleteCommand if you want to delete existing records. You can write those yourself or, if the conditions are right, you can use a command builder to do it for you.
If your query is based on a single table and you want to insert/update all the columns you retrieve back to that same table then a SqlCommandBuilder may be your best bet. You simply pass in the query and the command builder will use it to generate the action commands. That gives you limited flexibility but if you're just doing single-table operations then you don't need that added flexibility.
Such a method might look something like this:
Public Sub SaveChanges(tableName As String, data As DataSet)
Dim query = "SELECT * FROM " & tableName
Using adapter As New SqlDataAdapter(query, "connection string here")
Dim builder As New SqlCommandBuilder(adapter)
adapter.Update(data, tableName)
End Using
End Sub
I did what you said, but when I open the Form again, the new data are not there.
I made some changes in the code, perhaps because it did not work
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
BindingSource1.EndEdit()
ds.AcceptChanges()
db.SaveChanges("departamentos", "INSERT INTO departamentos VALUES('', " & TextBox2.Text & ")", ds)
ds = db.consulta("departamentos")
End Sub
And the code in the Module
Function SaveChanges(tableName As String, query As String, data As DataSet)
Using adapter As New SqlDataAdapter(query, "Data Source=NOTEBOOK\SQLEXPRESS;Initial Catalog=SysMarket;Persist Security Info=True;User ID=admin;Password=XXXXX")
Dim builder As New SqlCommandBuilder(adapter)
adapter.Update(data, tableName)
Return True
End Using
End Function

Data type mismatch in criteria expression when querying database

I'm a student currently doing my programming coursework. I am trying to get the MemberID from the Access database using a button in my DataGridView, but I end up with an error Data type mismatch in criteria expression when I select the member I wish to view. This is my code below:
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim Member As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
da = New OleDb.OleDbDataAdapter(Query, Conn)
Connect = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = \\DRS-SR-002\RMShared Documents\Computer Programming\Programs\year13\Kevin\Project\Database tables\DBTables.accdb"
Conn = New OleDb.OleDbConnection(Connect)
If e.ColumnIndex <> 4 Then
Exit Sub
End If
Dim MemberSelectedID As String = DataGridView1.Rows(e.RowIndex).Cells(0).Value
GroupBox1.Show()
Query = "SELECT MemberID FROM tblMember WHERE [MemberID] = """ & MemberSelectedID & """"
Conn.Open()
da = New OleDb.OleDbDataAdapter(Query, Conn)
da.Fill(ds, "Selected Member")
Conn.Close()
Member = ds.Tables("Selected Member").Rows(0).Item(0)
TextBox1.Text = Query
End Sub
Your Query is wrong.
It should be like this.
Query = "SELECT MemberID FROM tblMember WHERE [MemberID] = " & MemberSelectedID
OR
Query = "SELECT MemberID FROM tblMember WHERE [MemberID] = '" & MemberSelectedID & "'"
MemberID field is Integer so no need to specify it as string.
In SQL Server single quote ' is used to specify string not double quote ".
You are getting the MemberSelectedID from the DataGridView as String and then using it to query the database, on which I assume that it is defined as Numeric. That's the reason of the data type mismatch error
Try:
Dim MemberSelectedID As Integer = DataGridView1.Rows(e.RowIndex).Cells(0).Value
And
Query = "SELECT MemberID FROM tblMember WHERE MemberID = " & MemberSelectedID