VB NET - Select * From issue - sql

I have some wierd exception.
I have Access database with 2 tables, one named MYSB_DB and the other Employee.
I'm using the code below when I want to filter on something like that:
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String = String.Empty '
Dim pName As String = String.Empty
Dim fName As String = String.Empty
Dim ColpName As String = String.Empty
Dim ColfName As String = String.Empty
Dim ch As Integer = InStr(1, cmbEmployees.Text, " ", CompareMethod.Text)
pName = cmbEmployees.Text.Substring(0, ch)
fName = cmbEmployees.Text.Substring(ch, cmbEmployees.Text.Length - ch)
ColpName = "שדה1"
ColfName = "שדה2"
sql = "SELECT * FROM Employee WHERE [" & ColpName & "]=" & pName & ";"
da = New OleDb.OleDbDataAdapter(sql, Me.EmployeeTableAdapter.Connection.ConnectionString)
da.Fill(ds, Me.MYSB_DataBaseDataSet1.Employee.TableName)
I only change between the tables name in the code.
When I'm using this code for MYSB_DB table, the code is running well, but when I'm using the code for Employee table, I have an exception.
Any ideas why it's happening?

pName is a string, so it must be quoted:
sql = "SELECT * FROM Employee WHERE [" & ColpName & "]='" & pName & "';"

Related

How to Search a String with spaces in between

i am new to VB. so when i run my program and search for the name . i want to search with any spaces in between. For example i want to search " Brian Tracy" like that
i am quite confused on the string function that would do that. Thank you for your help
This is the code am working on
Dim search As String = txtAuthorsName.Text
'Search Sql For Authors Data
Dim conn As New
OleDb.OleDbConnection("Provider=Microsoft.ACE.OleDb.12.0;Data Source=" +
Server.MapPath("~/Access/bookstore.accdb"))
conn.Open()
Dim sql As String = "SELECT AID, authorName, authorSex FROM Authors"
Dim cmd As Object
If searchAuthor.SelectedValue.Equals("Name") Then
If search.Length > 0 Then
Dim keywords As String() = search.Split(" ")
sql = "SELECT * FROM Authors where authorName like '%" & keywords(0) & "%'"
For k As Integer = 1 To keywords.Length - 1
sql += " or authorName Like '%" & keywords(k) & "%'"
Next
End If
cmd = New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#authorName", "%" + txtAuthorsName.Text + "%")
Else
sql += "WHERE authorSex LIKE #authorSex"
cmd = New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#authorSex", "%" + txtAuthorSex.Text + "%")
End If
Dim dbread = cmd.ExecuteReader()
GridView2.DataSource = dbread
GridView2.DataBind()
dbread.Close()
conn.Close()
This is an example on how to filter/search data :
Public Sub FilterData(valueToSearch As String)
'
Dim searchQuery As String = "SELECT * From Users WHERE CONCAT(fname, lname, age) like '%" & valueToSearch & "%'"
Dim command As New SqlCommand(searchQuery, connection)
Dim adapter As New SqlDataAdapter(command)
Dim table As New DataTable()
adapter.Fill(table)
DataGridView1.DataSource = table
End Sub
Private Sub BTN_FILTER_Click(sender As Object, e As EventArgs) Handles BTN_FILTER.Click
FilterData(TextBox1.Text)
Make necessary changes, hope it works

Trouble building an SQL Query from VB.NET checklistbox options

I am trying to create an sql query from options selected in a checkListBox. The user will select all of the modules they want (in the checklistbox) to include data from, it will then build the query to collect this data. They will also enter a range for a rating value that will be included in the query. I am very new to using sql so I am struggling to understand what operator is missing from the final query.
This is what I have at the moment:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim h As Integer
Dim queryString As String
Dim moduleArray(6) As String
Dim counter As Integer = 0
Dim provider As String
Dim database As String
Dim connString As String
Dim moduleLen As Integer = 0
Dim moduleString As String = ""
Dim sqlquery As New OleDb.OleDbCommand
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Change the following to your access database location
database = "C:\Users\mello_000\OneDrive\Google Drive\Computing\Exampapergenerator\users.accdb"
connString = provider & database
Dim myConnection As OleDbConnection = New OleDbConnection(connString)
myConnection.Open()
sqlquery.Connection = myConnection
For h = 0 To h = 6
For Each item As String In Me.CheckedListBox1.CheckedItems
moduleArray(moduleLen) = item
If moduleArray(moduleLen) = "" Then
Else
moduleLen = moduleLen + 1
End If
Next
Next
For i = 0 To moduleLen
If i = 0 Then
moduleString = "'" & moduleArray(i) & "'"
ElseIf i > 0 Then
moduleString = moduleString & "'OR'" + "'" & moduleArray(i) & "'"
End If
Next
queryString = ("SELECT QText FROM Question WHERE QModule = '" & moduleString & "' AND QRating BETWEEN '" & TextBox1.Text() & "'AND'" & TextBox2.Text())
sqlquery.CommandText = queryString
sqlquery.ExecuteNonQuery()
End Sub
However I am getting the output to be: "SELECT QText FROM Question WHERE QModule = ''C1''OR''C2'' AND QRating BETWEEN '1'AND'2"
and an error:
Syntax error (missing operator) in query expression 'QModule = ''C1''OR''C2'' AND QRating BETWEEN '1'AND'2'.
Also, what would be the best way of outputting all of the returned data in a numbered list, in a form that would be printable?
Why are you doing this For h = 0 To h = 6 instead of just For h = 0 To 6?
You don't need single quotes around "'OR'" just use " OR ".
And your SQL syntax is wrong. This QModule = ''C1''OR''C2'' either needs to be QModule = 'C1' OR QModule = 'C2' or a better way QModule IN ('C1','C2')
Assuming QRating is numeric, you don't need single quotes. This QRating BETWEEN '1'AND'2' should be QRating BETWEEN 1 AND 2.
Also you should look into using SQL parameters so you don't have to worry about quotes or escaping them if you have quotes in your data.

SQL Data type mismatch in criteria expression

When running the expression below I get an error saying:
Data type mismatch in criteria expression
The message boxes are used to identify where error happened, it gets to checkpoint 1 then it stops!
Dim table2 As New DataTable
Dim recordcount2 As Integer
Dim command2 As String = "SELECT * FROM [Results] where " & "[TestID] = " & " '" & CInt(LocationID) & "'"
Dim adapter2 As New OleDb.OleDbDataAdapter(command2, conn)
table2.Clear()
MsgBox("Checkpoint 1")
recordcount2 = adapter2.Fill(table2)
MsgBox("Checkpoint 2")
The code is in this section of my program:
Try
'Defining variables
Dim table As New DataTable
Dim command As String
Dim recordCount As Integer
Dim LocationID As Integer
command = "SELECT * FROM [Test] where " & "[MachineID] = " & " '" & machineID & "'" 'SQL command to find if there is a usename stored with that is in username text box
Dim adapter As New OleDb.OleDbDataAdapter(command, conn) 'adapter
table.Clear() 'adding data to a table.
recordCount = adapter.Fill(table)
If recordCount <> 0 Then
For i = 0 To recordCount
Try
LocationID = CInt(table.Rows(i)(0))
Dim table2 As New DataTable
Dim recordcount2 As Integer
Dim command2 As String = "SELECT * FROM [Results] where " & "[TestID] = " & " '" & CInt(LocationID) & "'"
Dim adapter2 As New OleDb.OleDbDataAdapter(command2, conn)
table2.Clear()
MsgBox("Checkpoint 1")
recordcount2 = adapter2.Fill(table2)
MsgBox("Checkpoint 2")
If recordcount2 <> 0 Then
For x = 0 To recordcount2
MsgBox("yay1")
Dim TestID As String = table2.Rows(x)(1)
Dim Thickness As String = table2.Rows(x)(2)
Dim TargetFilter As String = table2.Rows(x)(9)
Dim SNR As String = table2.Rows(x)(3)
Dim STD As String = table2.Rows(x)(4)
MsgBox("yay2")
Dim M1 As String = table2.Rows(x)(5)
Dim M2 As String = table2.Rows(x)(6)
Dim kVp As String = table2.Rows(x)(7)
Dim mAs As String = table2.Rows(x)(8)
MsgBox("yay3")
Dim CNR As Short = (CLng(M1) - CLng(M2)) / 2
MsgBox("Further")
dgvViewData.Rows.Add(TestID, Thickness, CStr(SNR), CStr(STD), CStr(M1), CStr(M2), kVp, mAs, CStr(CNR))
Next
Else
MsgBox("RIP")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Next
Else
MsgBox("There data for this machine.")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Code on button
Try
Dim table As New DataTable
Dim command As String
Dim recordCount As Integer
Dim TestNum As String = "1"
command = "SELECT * FROM [Results] where " & "[TestID] = " & " '" & CStr(TestNum) & "'"
Dim adapter As New OleDb.OleDbDataAdapter(command, conn)
table.Clear()
recordCount = adapter.Fill(table)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Your locationID parameter has to be a string to be concatenated into your select statement. I'm assuming its an integer which is causing your datatype mismatch.
I'm quite sure that your LocationID is an integer, thus should be concatenated as is, so the SQL should read:
Dim command2 As String = "SELECT * FROM [Results] where [TestID] = " & CStr(LocationID) & ""

VB.NET SQL Filter doesnt show NULL

Sub KlantenFilterZoeken(ByVal DataGridI As DataGridView, ByVal Tbl As String, ByVal NaamStraatHuisnummerBusnummerPostcodePlaatsTelefoon As String, ByVal DBCON As String)
Dim Delen() As String = NaamStraatHuisnummerBusnummerPostcodePlaatsTelefoon.Split("|")
Dim objConnection As New SqlConnection(DBCON)
Dim objDt As New DataTable
DataGridI.DataSource = Nothing
objConnection.Open()
Dim sSQL As String = "SELECT * FROM " & Tbl & " Where " & "KlantID Like #KlantID AND naam Like #naam AND straat Like #straat AND huisnummer Like #huisnummer AND postcode LIKE #postcode AND plaats LIKE #plaats AND telefoon LIKE #telefoon"
Dim objCommand As SqlCommand = New SqlCommand(sSQL, objConnection)
'Parameters
objCommand.Parameters.AddWithValue("#KlantID", "%" & Delen(0) & "%")
objCommand.Parameters.AddWithValue("#naam", "%" & Delen(1) & "%")
objCommand.Parameters.AddWithValue("#straat", "%" & Delen(2) & "%")
objCommand.Parameters.AddWithValue("#huisnummer", "%" & Delen(3) & "%")
objCommand.Parameters.AddWithValue("#postcode", "%" & Delen(4) & "%")
objCommand.Parameters.AddWithValue("#plaats", "%" & Delen(5) & "%")
objCommand.Parameters.AddWithValue("#telefoon", "%" & Delen(6) & "%")
Dim objAdapter = New SqlDataAdapter(objCommand)
Dim objAdap As SqlDataAdapter = New SqlDataAdapter(sSQL, objConnection)
objAdapter.Fill(objDt)
DataGridI.DataSource = objDt
DataGridI.Columns(0).Visible = True
objConnection.Close()
objConnection.Dispose()
End Sub
This is my code to filter a datagridview, It works but the problem is telephone numbers that have value NULL are "hidden" by this code and I don't want this:
http://i.stack.imgur.com/VpXra.png
How can I fix this
I'm not sure what you would like to do exactly. But if you are trying to avoid empty cells, you could do something like this.
Dim objAdapter = New SqlDataAdapter(objCommand)
Dim objAdap As SqlDataAdapter = New SqlDataAdapter(sSQL, objConnection
objAdapter.Fill(objDt)
Dim i As Integer = objDt.Rows.Count
For i = 0 To objDt.Rows.Count Step 1
If (String.IsNullOrEmpty(objDt.Rows(i)("telefoon"))) Then
Dim phValue = "NULL"
objDt.Rows(i)("telefoon") = phValue
End If
Next
DataGridI.DataSource = objDt
DataGridI.Columns(0).Visible = True
objConnection.Close()
objConnection.Dispose()

Syntax error (comma) in query expression, header with commas

I am trying to check if value from label1 exist in dbf file column named : "NALOG,C,8". Header in DBF file I can not change, 'cause it represents column's format and field size. But with that I get this error : "Syntax error (comma) in query expression "NALOG,C,8 = #NAL"
Here is complete code :
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim FilePath As String = "C:\"
Dim DBF_File As String = "PROMGL"
Dim ColName As String = "NALOG,C,8"
'Dim SQLstr As String = "SELECT * FROM " & DBF_File
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV;User ID=Admin;Password="
'cmd = New OleDbCommand("SELECT * FROM " & DBF_File)
cmd = New OleDbCommand("SELECT * FROM PROMGL WHERE " & ColName & " = #NAL")
cmd.Connection = con
con.Open()
cmd.Parameters.AddWithValue("#NAL", Label1.Text)
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
con.Close()
Label6.Text = "EXIST" & TextBox1.Text
TextBox1.Text = ""
TextBox1.Focus()
Else
Label6.Text = "DOESN'T EXIST"
End If
end using
Thanks.
If you have a column that is named this:
Dim ColName As String = "NALOG,C,8"
Then I would change it too this:
Dim ColName As String = "[NALOG,C,8]"
Use this instead:
Dim ColName As String = "NALOG"