VB.Net SQLite Select Statement with Single Quote Error - vb.net

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 %''%.

Related

String error when adding items from a listbox to an access database

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.

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)

the user must match to the 3 fields

Dim elem As String
elem = "Grade School"
Dim v As Integer
v = 0
Dim con As New SqlConnection("SERVER=ANINGDZTS-PC;DATABASE=AEVS;Trusted_Connection = yes;")
Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM tbl_Voter WHERE Department, VotersID = '" & elem & "''" & txt_PwordElem.Text & "'AND Voted ='" & v & "'", con)
con.Open()
Dim sdr As SqlDataReader = cmd.ExecuteReader()
Try
If (sdr.Read() = False) Then
high()
Else
MessageBox.Show("WELCOME!")
elemBallot.Show()
Me.Hide()
End If
Catch EX As Exception
MsgBox(EX.Message)
End Try
End Sub
this code is not working, an error appear," An expression of non-boolean type specified in a context where a condition is expected, near ','."
Instead of trying to create your SQL query via concatenating strings, which is prone to errors, a much better way is to use parametrized query. Change your SqlCommand declaration to
Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM tbl_Voter WHERE Department = #Department AND VotersID = #VotersID AND Voted = #Voted", con)
cmd.Parameters.AddWithValue("#Department", elem)
cmd.Parameters.AddWithValue("#VotersID", txt_PwordElem.Text)
cmd.Parameters.AddWithValue("#Voted", v)
Bonus: Avoid SQL Injection
P.S. Please don't forget to close your Reader and Connection after the use.
P.P.S. If you simple need to make sure that specific row in table "tbl_Voter" exists or not based on your parameters (which is, judging by the code what you're doing) - using DataReader is overkill. Consider query like SELECT 1 FROM tbl_Voter ... and use of ExecuteScalar to check returned value for Nothing

get column value according to another column value from datatable in vb.net

i have a datatable similar to this:
id msg
1 thank you..
2 kindly...
3 please insert..
4 please stop
i need to get a msg according to a specific id from the datatable that's how i'm filling my datatable:
msgTable = selectMsg()
MsgBox(i need to get the msg here)
Public Function selectMsg() As DataTable
Dim command As SqlCommand = New SqlCommand("selectMsg", cn)
command.CommandType = CommandType.StoredProcedure
Dim da As New SqlDataAdapter(command)
'If dt.Rows.Count <> 0 Then
' dt.Rows.Clear()
'End If
Try
da.Fill(msgDS, "N_AI_HOME_CARE")
msgDT = msgDS.Tables(0)
Catch ex As Exception
logFile("SP selectMsg ---" + ex.Message)
End Try
Return msgDT
End Function
any suggestion will be much appreciated !
Supposing that your stored procedure returns the whole datatable of your messages (a very bad move because if the table is big you could have performance and network problems) then you need to apply the Select method with a filter expression to your returned datatable
msgTable = selectMsg()
Dim rows() = msgTable.Select("ID = " & idOfMessage)
if rows.Length > 0 then
MsgBox(row(0)(1).ToString()) ' read the first row, second column of the table'
End If
But I think you should use a more correct approach using a simple ExecuteScalar that doesn't return the entire datatable but just the first row and first column of a query
Public Function selectMsg(idOfMessage as Integer) As String
Dim command As SqlCommand = New SqlCommand("SELECT msg from tableName where ID = #id", cn)
command.Parameters.AddWithValue("#id", idOfMessage)
Dim result = command.ExecuteScalar()
if string.IsNullOrEmpty(result) Then
result = "No message found"
End If
return result
End Function
well acctually i just found that you use
MsgBox(msgTable.Rows(0)(1).ToString())
without any select method :)

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