WHERE Statement in VB. NET OleDB / SQL Query - sql

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()

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) & "')"

vb.net Listboxes and sql

I have 4 List boxes that I check,the contents of which go to make up the variables that get placed into the sql statement.This works fine.The problem is I have to check ALL of the boxes.If I leave any of the boxes out the sql statement doesn't work. I Did try adding "" to the listbox but this didn't work and it looked messy.Is there a way around this.Many Thank Jim
HERE IS MY CODE:
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.Odbc
Imports System.Data.DataTable
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim tables As DataTableCollection = ds.Tables
Dim source1 As New BindingSource()
Dim da As New OleDb.OleDbDataAdapter
Dim sql As String
Dim aa As String = authorList.Text
Dim bb As String = publisherList.Text
Dim cc As String = yearpublishedList.Text
Dim dd As String = genreList.Text
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source =C:\Documents and Settings\james\Desktop\Authors.accdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM books WHERE author = '" & aa & "' AND publisher = '" & bb & "' AND yearpublished = '" & cc & "' AND genre = '" & dd & "' "
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Authors")
Dim view1 As New DataView(tables(0))
source1.DataSource = view1
DataGridView1.DataSource = view1
DataGridView1.Refresh()
'MsgBox("OPEN FOR LUNCH")
'MsgBox("CLOSED FOR THE DAY")
con.Close()
End Sub
End Class
You are parsing the checkboxes into a string, so when you do that, you get:
1,2,3,4,5,6,7
If you do not select one checkbox, it will look like this:
1,2,3,,5,6,7
So SQL will break
Several ways you can approach this to solve the issue, so I'm not going to attempt one. But this should hopefully explain to you what happens and why it happens so you can go ahead and fix

VB SQL ACCESS Select Where Like Statement

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 %

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

Visual Basic HowTo: Retrieve Data from .mdf

What am I doing wrong? I have been going at this for a while now... I surrender.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using sqlCon = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\gadgetDatabase.mdf;Integrated Security=True")
Dim Id As Integer = 2
'With the use of ID, it will get the appName or Application Display Name
sqlCon.Open()
Dim sqlText = "SELECT appName " & _
"FROM appTable " & _
"WHERE Id = #sqlID"
Dim sqlCmd = New SqlCommand(sqlText, sqlCon)
sqlCmd.Parameters.AddWithValue("#sqlID", Id)
'sqlCmd.ToString()
sqlCmd.ExecuteScalar() 'I had these in there before I copied the code over
sqlCon.Close()
Label3.Text = sqlText 'For testing or confirmation it went correctly...
End Using
End Sub
You forgot to call
string apName = sqlCmd.ExecuteScaler();
and retrieve the result.
If a resultset (multiple results) is expected, then call reader = cmd.ExecuteReader() and loop through the results.