String error when adding items from a listbox to an access database - vb.net

I am trying to add the items in a list box to an access database. However at first, I was getting an error message saying the syntax was missing but now, I seem to get Conversion from string "" to type 'Double' is not valid ERROR. I've researched into this and it says it's because there may be a textbox empty but the listbox has many items in it which is what I'm not sure on.
Help will be appreciated, thanks.
Dim vari1 As String
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
MyConn.Open()
Dim cmd1 As OleDbCommand = New OleDbCommand(str1, MyConn)
Try
For i As Integer = 0 To LstOrderItems.Items(i) - 1
vari1 = LstOrderItems.Items.Item(i).ToString
cmd1.CommandText = ("insert into RestaurantData ([Food Order]) VALUES(" + vari1 + ")")
cmd1.ExecuteNonQuery()
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
MyConn.Close()
End If

It appears this line is your problem:
For i As Integer = 0 To LstOrderItems.Items(i) - 1
You're trying to read the item at index i (which is currently 0) as a number to loop to.
I think what you meant to write was this:
For i As Integer = 0 To LstOrderItems.Items.Count - 1
As for your database error you are missing two single quotes. When inserting data you must surround every value inside VALUES() with single quotes.
For instance:
INSERT INTO table_name (column1, column2, column3) VALUES('column1 value', 'column2 value', 'column3 value')
So to fix your error you must add those single quotes as well:
cmd1.CommandText = ("insert into RestaurantData ([Food Order]) VALUES('" + vari1 + "')")
Though you should really look into Parameterized queries (aka Prepared statements) since your code is vulnerable to SQL Injection.
See How do I create a parameterized SQL query? Why Should I? for more info.

Related

VB.Net SQLite Select Statement with Single Quote Error

I have an SQLite table with a column that contains entries that have already had any single-quote characters doubled to escape them. An example is:
MD Prince George''s
I want to query this table to see if I can find the above entry. This code shows a small test program to attempt to do this:
Private Sub TEST2_Click(sender As Object, e As EventArgs) Handles TEST2.Click
Dim sql() As String = {"LIKE 'MD Prince George%';",
"= 'MD Prince George''s';",
"= 'MD Prince George's';"}
Dim ThisTable As New List(Of DataRow)
For a As Integer = 0 To sql.Count - 1
Try
Connect(2) ' Getting my connection
Using tr As SQLiteTransaction = conn.BeginTransaction
Using cmd As New SQLiteCommand
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT * FROM `counties` WHERE `STATE_COUNTY` " & sql(a)
Using da As New SQLiteDataAdapter(cmd)
Dim dt As New DataTable
da.Fill(dt)
If dt.Rows.Count > 0 Then
ThisTable.Add(dt.Rows(0))
End If
End Using
End Using
tr.Commit()
End Using
Catch ex As Exception
Debug.WriteLine(ex.Message)
Finally
conn.Close()
End Try
Debug.WriteLine("Result(" & a & ": " & sql(a) & ") gives ThisTable.Count=" & ThisTable.Count)
Next
End Sub
The results are:
Result(0: LIKE 'MD Prince George%';) gives ThisTable.Count=1
Result(1: = 'MD Prince George''s';) gives ThisTable.Count=1
SQLite error (1): near "s": syntax error
Exception thrown: 'System.Data.SQLite.SQLiteException' in System.Data.SQLite.dll
SQL logic error
near "s": syntax error
Result(2: = 'MD Prince George's';) gives ThisTable.Count=1
This shows that the first statement was matched: I include it to prove there is such an entry in the table. The second statement, trying to match 2 single quotes with 2 single quotes, returns no result. The third statement, trying to match 2 single quotes with 1 single quote, returns an error.
My question: what should my select statement be to find the entirety of that single entry, or other entries which might have 2 single quotes in them? No, I don't want to only find %''%.

Insert Into Syntax error vb.net

Good Day
I am using VB 2017 to create an application. i am using an Access Database.
When i an running my code i get an Insert Into Syntax error
my code is as follows.
Please help.
Public Shared Function AddLocation(location As Location) As Integer
Dim connection As OleDbConnection = AutoBeautyCareDB.GetConnection
Dim insertStatement As String = "Insert Into Location (CUST#,HOSP_ID,FLOOR,ROOM) VALUES(?,?,?,?)"
Dim insertCommand As OleDbCommand = New OleDbCommand(insertStatement, connection)
insertCommand.Parameters.AddWithValue("Cust#", location.CustNo.ToString)
insertCommand.Parameters.AddWithValue("HospId", location.HospId.ToString)
insertCommand.Parameters.AddWithValue("Floor", location.Floor.ToString)
insertCommand.Parameters.AddWithValue("Room", location.Room.ToString)
Try
connection.Open()
insertCommand.ExecuteNonQuery()
Dim selectStatement As String = "Select ##Identity"
Dim selectCommand As New OleDbCommand(selectStatement, connection)
insertCommand.CommandText = selectStatement
Dim locationId As Integer = insertCommand.ExecuteScalar
Return locationId
Catch ex As OleDbException
Throw ex
Finally
connection.Close()
End Try
End Function
When you use a special symbol like # you need to enclose the field name between square brackets, however it is best to change that name to something less problematic
Dim insertStatement As String = "Insert Into Location
([CUST#],HOSP_ID,FLOOR,ROOM)
VALUES(?,?,?,?)"
Also remember that AddWithValue, while it seems to be a useful shortcut, has many problems as explained in the following article
Can we stop using AddWithValue already?
A single line approach with better parameter handling is the following
insertCommand.Parameters.Add("Cust#", OleDbType.Integer).Value = location.CustNo
(Assuming Cust# is an integer type in your database table)

how can I search data in set of columns with spaces in their names (ex- iron[space]man)

I want to search for a keyword on 4 columns like :
Dim con As OleDbConnection
Dim cmd As OleDbCommand
con=new OleDbConnection (connectionstring)
cmd=new OleDbCommand (Select * from DVD_INFO where slot 1 = ' "+TXTSearch .Text+" ' OR slot 2 = ' "+TXTSearch .Text+" ' ...etc)
con.open ()
dr=cmd.ExecuteReader
While dr.read
txtDVDno.Text = dr ("DVD no")
End While
con.Close ()
Error Message
syntax error (missing operator) in query expression 'Slot 1 = 'Iron Man"
MsgName is OleDbException was Unhandled
How can i fix this issue?
Field names with spaces should be enclosed in square brackets
cmd=new OleDbCommand (Select * from DVD_INFO where [slot 1] = ....."
Said that, start as soon as possible to use a parameterized query to avoid sql injection security problems and parsing problems
Dim cmdText = "Select * from DVD_INFO where [slot 1] = #search"
Using con=new OleDbConnection (connectionstring)
using cmd=new OleDbCommand (cmdText, con)
con.open()
cmd.Parameters.Add("#search", OleDbType.VarWChar).Value = TXTSearch.Text
Using dr=cmd.ExecuteReader()
While dr.read
txtDVDno.Text = dr("DVD no")
End While
End Using
End Using
End Using
Note that if you want to repeat the search on other fields you need to add another parameter for each condition also if it is the same value repeated more than one time. This is necessary with OleDb because this driver is not able to recognize the parameters by their placeholder name. It uses a strictly positional order and so, if you have two where condition you need to add two parameters to the collection no matter what is their name or value.
EDIT
If you want to execute the search having only a partial text you could use the LIKE operator in your query text and change the way in which you initialize the parameters adding the wildcard symbol %
Dim cmdText = "Select * from DVD_INFO where [slot 1] LIKE #search"
....
cmd.Parameters.Add("#search", OleDbType.VarWChar). Value = TXTSearch.Text & "%"
Of course the wildcard character could be added at the beginning of the searched text to give different meanings to your search text (field begins, ends, contains)

Data type mismatch in criteria expression. -Microsoft JET DATABASE ENGINE

In the code below, it was a "delete" button used in OLEDB connection.
My database table name is tblinformation.
Btw, the error shows:
Data type mismatch in criteria expression. `-Microsoft JET DATABASE ENGINE`, and it was in a form of msgbox..
Imports System.Data.OleDb
Imports System.String
Public Class frmbookinfo
Dim cnn As New OleDb.OleDbConnection
Dim Str As String
If CheckId() = False Then
MsgBox("Id : Integer Value Required!!!")
Exit Sub
End If
Try
Str = "delete from tblinformation where bcode="
Str += txtbookcode.Text.Trim
Con.Open()
Cmd = New OleDbCommand(Str, Con)
Cmd.ExecuteNonQuery()
Dst.clear()
Dad = New OleDbDataAdapter("SELECT * FROM tblinformation ORDER BY bcode", Con)
Dad.Fill(Dst, "tblinformation")
MsgBox("Record deleted successfully...")
If CurrentRow > 0 Then
CurrentRow -= 1
ShowData(CurrentRow)
End If
Con.Close()
Catch ex As Exception
MessageBox.Show("Could Not delete Record!!!")
MsgBox(ex.Message & " - " & ex.Source)
Con.Close()
End Try
Probably your field bcode in the database is of type text.
You use a string concatenation to build your command text and this cannot be helped if you fail to treat your values correctly.
Instead use parametrized queries and leave the task to correctly parse your parameters to the database framework code
Str = "delete from tblinformation where bcode=?"
Con.Open()
Cmd = New OleDbCommand(Str, Con)
Cmd.Parameters.AddWithValue("#p1", txtbookcode.Text.Trim)
Cmd.ExecuteNonQuery()
Now your sql command contains a parameter placeholder (?) and the correct parameter value is assigned in the parameter collection. The framework code handles correctly this parameter
EDIT If your bcode field is a text field, you cannot build your command in that way. You should encapsulate your value between single quotes. Something like this.
IT WORKS BUT IT IS WRONG - VERY WRONG -
Str = "delete from tblinformation where bcode='" & txtbookcode.Text.Trim & "'"
But this is wrong from the start.
First - If your txtbookcode contains a single quote, the whole
command text becomes invalid and you get a Syntax Error
Second - String concatenation is bad because you can't trust your user.
If it enters some malicious text you could face a Sql Injection
problem
So, I really suggest you to use the parametrized query approach illustrated in the first example

Selecting an integer from an Access Database using SQL

Trying to select an integer from an Access Database using an SQL statement in VB
Dim cmdAutoTypes As New OleDbCommand
Dim AutoTypesReader As OleDbDataReader
cmdAutoTypes.CommandText = "SELECT * FROM AutoTypes WHERE TypeId = '" & cboTypeIds.Text & "'"
AutoTypesReader = cmdAutoTypes.ExecuteReader
Error message says: "OleDbException was unhandled: Data type mismatch in criteria expression." and points to the AutoTypesReader = cmdAutoTypes.ExecuteReader line
Rather make use of OleDbParameter Class
This will also avoid Sql Injection.
You don't need the quotes in the query string. You're searching for a number, not a string.
cmdAutoTypes.CommandText = "SELECT * FROM AutoTypes WHERE TypeId = " & cboTypeIds.Text
Hi In access SQL you can't use single quote around your Integer type.
so
command text will be.. "SELECT * FROM AutoTypes WHERE TypeId = " & cboTypeIds.Text & " and .... "
In Access SQL, don't quote numeric constants.
And test whether IsNull(cboTypeIds). You can't do what you were planning to do until a value has been chosen.
Do not use string concatenation when you build your SQL query, use parameters instead.
Dim cmd As OledbCommand = Nothing
Dim reader as OleDbDataReader = Nothing
Try
Dim query As String = "SELECT * FROM AutoTypes WHERE TypeId = #Id"
cmd = New OledbCommand(query, connection)
//adding parameter implicitly
cmd.Parameters.AddWithValue("#Id", cboTypeIds.Text)
reader = cmd.ExecuteReader()
Catch ex As Exception
Messagebox.Show(ex.Message, MsgBoxStyle.Critical)
End Try
You can also explicitly state the parameter data type.
cmd.Parameters.Add("#Id", OleDbType.Integer).Value = cboTypeIds.Text
Hope this helps.