VB.NET 2010 database search - sql

I have a ms access database connected to my vb application through the data wizard.
i want to allow the user to search the database and display their results on a datagrid.
for example user searches for 50 – 55 year Old man under 1.8 meters in height
so far i can display the total amount of people on the database with this code
Private Sub lblTotalPeople_Click(sender As System.Object, e As System.EventArgs) Handles lblTotalPeople.Click
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\AssignmentDatabase.accdb")
' Use wildcard'
Dim cmd As OleDbCommand = New OleDbCommand("Select COUNT(*) From Table1", con)
'' or Where username='" & TextBox1.Text & "'
con.Open()
Dim myDA As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim myDataSet As DataSet = New DataSet()
myDA.Fill(myDataSet, "Table1")
DataGridView2.DataSource = myDataSet.Tables("Table1").DefaultView
End Sub
how would i search the database based on what the user searches or what would i use?

Assuming you don't already you need to learn how to use SQL.
In your code above the SQL statement is
Select COUNT(*) From Table1
You would need to replace this SQL with a search that uses a value from the user (most likely from a textbox). This text
'' or Where username='" & TextBox1.Text & "'
appears to be part way to some SQL that may work but it looks dangerous. You should also research SQL Injection as using this directly means users could access/damage your Access database.

Related

Filter databound combobox based on value in another column from the same dataset

I am attempting to create a process scheduler as a project in school this summer and am quite new to using VB. Currently I have a combobox bound to the "EmployeeBindingSource" which holds information for every single employee in a company. Each employee is assigned a skill level for each work station in the building. What I would like to do is if an employee is listed as having "0" skill in say, the assembly station, when selecting an employee to assign to the assembly station, that particular employee will not appear in the combobox.
From doing some research I believe that rather than binding the combobox to the data source in the designer, I will have to assign values to the each combo box in the code on a form load.
This is the access table that holds all the employee information
In the table we can see that Steve has a skill level of "0" in the AS_Level category (assembly).
However, here we can see that he still appears as an option for the assembly area when creating a new project
Currently all the data binding happens in the designer for each combo box and therefore no code has been written for the data binding. At the moment each combo box is bound to the "Full_Name" column in the access table.
Again, I am quite new to VB so I apologize if this is too vague. Let me know if I can give any more helpful information. Thank you all in advance.
After adding the code suggested here is what I have
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
datafile = "C:\Users\Jacob\Desktop\Halton\HaltonProject.accdb"
connString = provider & datafile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "SELECT * FROM [Employee] WHERE (SP_Level <> '" & 0 & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
Dim dr As OleDbDataReader = cmd.ExecuteReader
Dim userfound As Boolean = False
Dim Full_Name As String
While dr.Read
userfound = True
Full_Name = dr("Full_Name").ToString
SP_Emp1.Items.Add(Full_Name)
SP_Emp2.Items.Add(Full_Name)
SP_Emp3.Items.Add(Full_Name)
SP_Emp4.Items.Add(Full_Name)
End While
myConnection.Close()
Works completely now!
Based on your comments and post, I assume, the checkboxes on the left enable/disable the comboboxes on that row, and since you're binding them individually if you change your query so it looks like this:
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Employee] WHERE AS_Level <> 0 , myConnection) Dim dr As OleDbDataReader = cmd.ExecuteReader
Note that the where clause will vary depending on your needs, so it could be WHERE AS_Level <> 0 or WHERE SP_Level <> 0 and so on.
I have never used an Ole database so I'm not quite sure about the syntax, hope this helps.

I am trying to find out how to compare two dates in a visual basic database

I currently have a visual basic database made in Microsoft access. In this database, I allow the user to enter a date in a text box and this date gets saved to the database. I want to compare the dates "on the database!". The hard part is that the dates are entered in the same text box but saved on different rows. I need to compare the different dates in the rows of the database.
Fetch data from the database and use FOR EACH loop to compare. A sample code is as follows:
Dim con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;DataSource=Test.accdb;Persist Security Info=False;")
con.Open()
Dim cmd As New OleDbCommand("SELECT date_col FROM my_table", con)
cmd.CommandType = CommandType.Text
Dim reader As OleDbDataReader = cmd.ExecuteReader()
Dim dt As DataTable = reader.GetSchemaTable()
For Each row As DataRow In dt.Rows
If row.Item("date_col") = **your_criteria** Then
**your_other_statements**
End if
Next row
con.Close()
Hope this will help

Executing delete command on MS-Access through VB.NET does not delete the records

Just trying to delete all rows of an Access table:
Private Sub btnImport_Click(sender As Object, e As EventArgs) Handles btnImport.Click
'Clear old records from extract table
Dim sqlConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\CLI_CRVM.accdb")
Dim cmd As New System.Data.OleDb.OleDbCommand()
Dim intRC As Integer
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "DELETE * FROM [extract] ;"
cmd.Connection = sqlConnection
sqlConnection.Open()
intRC = cmd.ExecuteNonQuery()
sqlConnection.Close()
MsgBox(intRC)
End Sub
I do not get any errors but it doesn't delete the rows either. There are currently 10 rows in the table and the MsgBox shows 10 each time the button is clicked and there are still 10 rows in the table afterwards.
What am I missing?
Try without the asterisk:
DELETE FROM [extract];
You don't generally supply any columns in a DELETE. You only supply columns that you want to match a row against .. via a WHERE clause afterwards.
There are certain dialects of SQL that let you specify thresholds on what you delete in that part of the query - however, I don't believe Access' dialect does (I could be wrong).

Visual studio Access DB insert id thats bigger as previous id

Good day reader,
i have a question about vb access insert, I have an id, but I what the next insert id to automatically get a higher number. this is the code I have so far:
Try
Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\data\testing.Accdb;Persist Security Info=False;")
If cn.State = ConnectionState.Open Then
cn.Close()
End If
cn.Open()
Dim sSQL As String = "insert into tabel1(id) values(#d1)"
Dim cmd As OleDbCommand = New OleDbCommand(sSQL, cn)
Dim id As OleDbParameter = New OleDbParameter("#d1", OleDbType.VarWChar, 25)
id.Value = 'so here I need the automatic higher number
cmd.Parameters.Add(id)
I really hope one of you guys can help me with this, thanks already.
sorry for my bad English it because I’m Dutch, if have any question I’ll try to explain it.
regards Tom
You can do this with a nested sub query:
INSERT INTO Table1 (Id,Test) SELECT TOP 1 MAX(ID) + 1,"Test Value" FROM Table1;
In this example I added another field called "Test" so you can see how you would enter values for the other fields.

Select Statement SQL in VB

I understand that there are other posts such as this, however I cannot find one that will work for me and Im really at the end of my tether with this, I really dont know what to do.
I have a few tables with ID columns and name columns, that are connected by Link Tables through foreign keys etc. I'm trying to enter data into the database via a GUI and to do so I'm using insert statements into the 'regular' tables, then Select statements to get the autogen IDs from the regular table to then insert into the link tables.
The code below is what I've been trying to use to do this.
Imports System.Data.SqlClient
Public Class Test
Private cs As New SqlConnection(".....")
Private Sub btnInsertNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsertNext.Click
Dim ContID As Integer
Dim FName As Integer
cs.Open()
Using command As New SqlCommand("Select FamID From Family Where Name = '" & FName & " '", cs)
command.Parameters.AddWithValue("#FamID", ContID)
command.ExecuteNonQuery()
End Using
Using command As New SqlCommand("Select DocID From Doctors Where DocName LIKE'" & AddFam.Doctor & " '", cs)
command.Parameters.AddWithValue("#DocID", AddFam.Doctor) ''AddFam is another form I'm using to add a family member to a Doctor
command.ExecuteNonQuery()
End Using
cs.close()
I'm using:
VB 2010
SQL server management 2008 r2
I understand its a bit muddley but any help would be greatly appreciated, and I'm sorry if this has come up before.
It's not really clear what problem you actually have, i assume that you don't know how to retrieve newly generated IDs.
Here is an self-explanatory example on how to retrieve new identity values with ADO.NET:
Using con = New SqlConnection(connectionString)
Dim newID As Int32
Using insertCommand = New SqlCommand("INSERT INTO Test(Value)VALUES(#Value);SELECT CAST(scope_identity() AS int)", con)
insertCommand.Parameters.AddWithValue("#Value", "Value1")
con.Open()
newID = DirectCast(insertCommand.ExecuteScalar, Int32)
End Using
If newID <> 0 Then
Using updateCommand = New SqlCommand("UPDATE TEST SET Value='Value1.1' WHERE idTest=#idTest", con)
updateCommand.Parameters.AddWithValue("#idTest", newID)
If con.State <> ConnectionState.Open Then con.Open()
Dim updatedRecordCount = updateCommand.ExecuteNonQuery
End Using
End If
End Using
The 2 important parts are:
SELECT CAST(scope_identity() AS int)
which will return the new identity value
DirectCast(insertCommand.ExecuteScalar, Int32)
which will return the new Identity column value if a new row was inserted, 0 on failure.
Since you're mixing using parameters with string-concatenation: using parameters is very important because it will prevent SQL-Injection.
SCOPE_IDENITY
ExceuteScalar-Method
Commands and Parameters in ADO.NET
NO! Parameterise your queries like this.
command = New SqlCommand("Select FamID From Family Where Name = #Fname", cs)
command.Parameters.AddWithValue("#Fname", ContID)
FamID = command.ExecuteScalar()
And ideally, you should use Scope_Identity() to get the Identity from you insert statement
You can try with this code on two queries based on # symbol
...
Using command As New SqlCommand("Select FamID From Family Where Name = #FamID", cs)
command.Parameters.AddWithValue("#FamID", ContID)
...
Using command As New SqlCommand("Select DocID From Doctors Where DocName LIKE #DocID", cs)
command.Parameters.AddWithValue("#DocID", AddFam.Doctor)
...