VB SQL ACCESS Select Where Like Statement - sql

Net, i'm trying to learn how to display a query result into data grid whenever i click the Search Button as a trigger event for the query.
But nothing happens when i click the Search Button but gives me an error message (Please see link for the screenshot of error message) which i don't understand.
Error: http://s1.postimg.org/di091riv3/error1.jpg
Can you please point me to the right track, Thanks.
Here is my code below
Imports System.Data.OleDb
Public Class SearchForm
Dim con As New OleDbConnection
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Statd.SelectedIndexChanged
End Sub
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
con.Open()
Dim sqlQuery As String
Dim sqlCommand As New OleDbCommand
Dim sqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
Dim empNum As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
empNum = eNumText.Text
empLname = empLnameText.Text
empDept = Deptd.Text
empStat = Statd.Text
sqlQuery = "SELECT * FROM tbl_empinfo WHERE LastName like '% " & empLnameText.Text & "' "
' MsgBox("Employee Number " + empNum + empLname + empDept + empStat) 'test statement
With sqlCommand
.CommandText = sqlQuery
.Connection = con
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(Table)
End With
For i = 0 To Table.Rows.Count - 1
With DataGridView1
.Rows.Add(Table.Rows(i)("EmpID"), Table.Rows(i)("FirstName"), Table.Rows(i)("LastName"), Table.Rows(i)("Department"), Table.Rows(i)("Position"), Table.Rows(i)("Status"), Table.Rows(i)("Years"))
End With
Next
End With
con.Close()
End Sub

Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
sqlQuery = "SELECT * FROM tbl_empinfo WHERE LastName like '%' + ? + '%' "
'It's counter-intuitive, but it's best in .Net to use a new connection object each time
Using con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"), _
cmd As New OleDbCommand(sqlQuery, con)
'Use actual column type and length here
cmd.Parameters.Add("?", OleDbType.NVarChar, 50).Value = empLnameText.Text
con.Open()
DataGridView1.DataSource = cmd.ExecuteReader()
End Using
End Sub

Try to change the % to * in your query, just like this:
sqlQuery = "SELECT * FROM tbl_empinfo WHERE LastName like '* " & empLnameText.Text & "' "
Access doesn't use % as wildcard:
http://www.techonthenet.com/access/queries/like.php

I spotted an error in the usage of %. It is used for SQL Server and Not Access SQL use * in place of %

Related

Read data from a database in vb.net

So I used this piece of sample code to retrieve data from a MS Access Database and display it on a few textboxes on the form. The following error occurs -
# dr = cmd.ExecuteReader - Data type mismatch in criteria expression.
dr = cmd.ExecuteReader
This is the sample code -
Dim provider As String
Dim dataFile As String
Dim connString As String
Public myConnection As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\example\Desktop\Data.accdb" ' Change it to your Access Database location
connString = provider & dataFile
myConnection.ConnectionString = connString
End Sub
Dim r As Random = New Random
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
myConnection.Open()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
Dim str As String
str = "SELECT * FROM Items WHERE (Code = '" & r.Next(1, 3) & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
TextBox1.Text = dr("Description").ToString
TextBox2.Text = dr("Cost").ToString
TextBox3.Text = dr("Price").ToString
End While
myConnection.Close()
End Sub
Try this ..
str = "SELECT * FROM Items WHERE (Code = '" & (r.Next(1, 3)).ToString() & "')"
try this:
str = "SELECT * FROM Items WHERE (Code = '" & cStr(r.Next(1, 3)) & "')"
The table name in the file that you provided for download is "Table1" not "Items".
Change the query string to:
str = "SELECT * FROM Table1 where (Code = '" & r.Next(1, 3) & "')"

specified cast is not valid

Here is a code that retrieve values from the database, but my problem is that it throws out an exception saying "InvalidCastException was unhandled specified cast is not valid". I am now confused what went wrong, The code and the table stated below.
Here is the code:
Public connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source =" & Application.StartupPath &
"\TestData.accdb; Persist Security info = false"
Public Conn As New OleDbConnection
Private Sub TestForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Loard
Conn.ConnectionString = connstring
Conn.Open()
LoadValue( )
End Sub
Private Sub LoadValue( )
Dim i As Integer
Dim cmd As OleDbCommand = New OleDbCommand
With cmd
.CommandText = "SELECT MAX(Guard_ID) FROM Guard"
.CommandType = CommandType.Text
.Connection = Conn
.ExecuteNonQuery()
Dim reader As OleDbDataReader = cmd.ExecuteReader
If reader.Read Then
TextBox1.Text = reader.GetString(0)
i = TextBox1.Text + 1
TextBox1.Text = i
reader.Close()
End If
End With
End Sub
The table reference:
Exception Error:
I am really confused now on why the code does not work, any help and advice will be gladly accepted. Thanks in advance.
try this,
Private Sub LoadValue()
Dim i As Integer
Dim cmd As OleDbCommand = New OleDbCommand
With cmd
.CommandText = "SELECT MAX(Guard_ID) FROM Guard"
.CommandType = CommandType.Text
.Connection = Conn
.ExecuteNonQuery()
Dim reader As OleDbDataReader = cmd.ExecuteReader
If reader.Read Then
Dim tmpVal As Object = reader.Item(0)
TextBox1.Text = IIf(IsDBNull(tmpVal), "0", tmpVal.ToString())
i = CInt(TextBox1.Text) + 1
TextBox1.Text = i.ToString()
reader.Close()
End If
End With
End Sub

getting variables into sql string from list box

I am having a problem trying to get the contents of a list box into and SQL string via a variable(moon)
Here are 3 SELECT strings from the main body of code below.The last two strings work fine
but the first one doesn't.That's the one where I try and place the variable into the code
I have tried a few variations on the code but nothing seems to work.Does anybody have any suggestions.
THE SQL STRINGS:
da = New OleDbDataAdapter("SELECT * FROM books WHERE [author] = '" & moon "' ", myConnection) 'fails
da = New OleDbDataAdapter("SELECT * FROM books", myConnection) 'works
da = New OleDbDataAdapter("SELECT * FROM books WHERE author = 'molly brown' ", myConnection) 'works{
MAIN CODE BODY
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.Odbc
Imports System.Data.DataTable
Public Class Form1
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Dim ds As DataSet = New DataSet
Dim da As OleDbDataAdapter
Dim tables As DataTableCollection = ds.Tables
Dim source1 As New BindingSource()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim moon As String
moon = ListBox1.Text
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Documents and Settings\james\Desktop\Authors.accdb" ' change to access database location on your computer
connString = provider & dataFile
myConnection.ConnectionString = connString
da = New OleDbDataAdapter("SELECT * FROM books WHERE [author] = '" & moon & "' ", myConnection) 'fails
'da = New OleDbDataAdapter("SELECT * FROM books", myConnection) 'works
'da = New OleDbDataAdapter("SELECT * FROM books WHERE author = 'molly brown' ", myConnection) 'works
da.Fill(ds, "books")
' replace "items" with the name of the table
' replace [Item Code], [Description], [Price] with the columns headers
Dim view1 As New DataView(tables(0))
source1.DataSource = view1
DataGridView1.DataSource = view1
DataGridView1.Refresh()
End Sub
End Class
Best practice is to use a new connection object for each call to the database, define objects with the smallest scope possible, and to use parameterized queries instead of substituting the value into your sql string.
Under no circumstances should you ever use string manipulation to put a user-selected value into your sql statement! Code like this is very bad:
da = New OleDbDataAdapter("SELECT * FROM books WHERE [author] = '" & moon & "' ", myConnection)
Imagine what would happen in this example if you have an author like "Patrick O'Neil". There are many ways this problem can be further abused to cause real damage to your database, application, and users. Just don't use string concatenation for this.
Do it like this instead:
Public Class Form1
Private Const provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Private Const dataFile As String = "C:\Documents and Settings\james\Desktop\Authors.accdb" ' change to access database location on your computer
Private connString As String = provider & dataFile
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ds As New DataSet()
'Set a special placeholder for your value as part of a *constant* sql statement
Dim sql As String = "SELECT * FROM books WHERE [author] = ? "
Using cn As New OleDbConnection(connString), _
cmd As New OleDbCommand(sql, cn), _
da As New OleDbDataAdapter(cmd)
'Set the value for that placeholder via a query parameter
'Parameters work best when you set the actual type and length
' to match your database. I had to guess at the length here.
cmd.Parameters.Add("?", OleDbType.NVarChar, 50).Value = Listbox1.Text
da.Fill(ds, "books")
End Using
DataGridView1.DataSource = ds.Tables("books")
DataGridView1.Refresh()
End Sub
End Class

How to get count of records in a table?

Someone help me
I am working on our project and I need to check if my DB has already 20 records.
If so, then it will not accept records anymore.
I've been trying the codes below:
Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim ds, ds2 As New DataSet
Dim da, da2 As OleDb.OleDbDataAdapter
Dim sql, sql1 As String
Dim int As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
con.ConnectionString = "Provider=Microsoft.jet.OLEDB.4.0; data source = |datadirectory|\Database6.mdb"
con.Open()
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Accounts WHERE Username='" & TextBox1.Text & "'", con)
Dim sdr As OleDb.OleDbDataReader = cmd.ExecuteReader
Dim cmd1 As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Accounts")
sql = "INSERT INTO Accounts ([Username], [Password], [FirstName], [LastName]) VALUES ('" & TextBox1.Text & "','" & TextBox2.Text & "', '" & TextBox3.Text & "','" & TextBox4.Text & "') "
sql1 = "SELECT Count([AccountID]) FROM Accounts"
cmd = New OleDb.OleDbCommand(sql, con)
cmd1 = New OleDb.OleDbCommand(sql1, con)
Convert.ToInt32(sql1)
cmd1.ExecuteScalar()
If sql1 < 20 Then
MsgBox("Cannot accept records")
ElseIf sdr.HasRows = False Then
cmd.ExecuteNonQuery()
MsgBox("Account Added")
ElseIf sdr.HasRows = True Then
MsgBox("Username is taken")
End If
con.Close()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Hide()
Form2.Show()
End Sub
End Class
But the convert code fires an error :
Input string was in incorrect format
But if I delete the convert code it gives me the error
Conversion from string "SELECT Count([AccountID]) FROM A" to type 'Double' is not valid."
Help me please.
TIA
I dont know VB all that well, this is from the top of my head. Your trying to convert your SQL text, which will never work. Try something like this:
dim result as object
result = cmd1.ExecuteScalar()
dim count as int
count = Convert.ToInt32(result)
If count < 20 Then

WHERE Statement in VB. NET OleDB / SQL Query

Thanks for taking the time to look at my question! I am new to all this and I am trying my best to work out the solution but I keep hitting a brick wall. I'm trying to update a table in a MDB file with the value of a String, where other conditions are met in another part of the table. I realise calling on strings is bad practise!
I think the problem is with the WHERE part of the SQL statement?
Appreciate any help, here is part of the code:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Declerations For Calling on
Dim AnimalHouse As String
AnimalHouse = "TestText"
Dim AddressForAssingment As Integer
AddressForAssingment = 1
Dim IDCheckAssignment As Integer
IDCheckAssignment = 1
'Connection Information
Dim myConnection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ProjectDirectory.Text)
Dim myCommand As New OleDbCommand("INSERT INTO IOInformation SET Description= '" & AnimalHouse & "' WHERE ID_number= '" & AddressForAssingment & "' AND ID_Check= '" & IDCheckAssignment & "'")
myCommand.Connection = myConnection
myConnection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()
End Sub
INSERT and UPDATE are two different commands.
Your query is a mix of both right now, what you want is possibly something like:
UPDATE IOInformation SET Description = .... WHERE ...
Like this. Please look into Parameterized Queries.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Declerations For Calling on
Dim AnimalHouse As String
AnimalHouse = "TestText"
Dim AddressForAssingment As Integer
AddressForAssingment = 1
Dim IDCheckAssignment As Integer
IDCheckAssignment = 1
'Connection Information
Dim myConnection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ProjectDirectory.Text)
Dim myCommand As New OleDbCommand("Update IOInformation SET [Description] = #animalHouse, WHERE ID_number = #addrForAssn AND ID_Check = #Id))
myCommand.Parameters.AddWithValue("#animalHouse", AnimalHouse)
myCommand.Parameters.AddWithValue("#addrForAssn", AddressForAssingment)
myCommand.Parameters.AddWithValue("#Id", IDCheckAssignment)
myCommand.Connection = myConnection
myConnection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()