Selecting specific table from database VB - vb.net

Public Sub UserList_SelectedIn(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UserList.SelectedIndexChanged
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "\users.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Chart1.Series.Add("Score") 'Adds the graph into the program
Dim cmdd As OleDbCommand = New OleDbCommand("SELECT [Score], [Month] FROM * WHERE Table ='" & UserList.SelectedItem, myConnection)
Dim dr2 As OleDbDataReader = cmdd.ExecuteReader
While dr2.Read
Chart1.Series("Score").Points.AddXY(dr2("Month").ToString, dr2("Score").ToString) 'Adds the month/score to the graph
End While
End Sub
Trying to find a way to make the following line of code allow me to select data from a specific table that the user can choose from a listbox.
Dim cmdd As OleDbCommand = New OleDbCommand("SELECT [Score] FROM * WHERE Table ='" & UserList.SelectedItem, myConnection)
It gives the error when running: Syntax error in FROM clause.
I'm guessing it's because of the * after FROM.

This should be a comment but I need 50+ rep to comment... but it should show you how to structure your query
SELECT [column] FROM [table] WHERE [condition]

I was just about to add comment to say you need another " ' " at the end of the command, but also, I've never seen FROM * used in a command like that. Not saying it's wrong, I just have never seen it :). Anyways, this should help out with the issue, dont forget to bracket tables and fields if they contain wildcards or spaces in the names. Brackets can be used even if do not contain spaces or wildcards.
Public Sub UserList_SelectedIn(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UserList.SelectedIndexChanged
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "\users.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Chart1.Series.Add("Score") 'Adds the graph into the program
Dim Table_Str As String = "[" & UserList.SelectedItem & "]"
Dim cmdd As OleDbCommand = New OleDbCommand("SELECT [Score], [Month] FROM " & Table_Str, myConnection)
Dim dr2 As OleDbDataReader = cmdd.ExecuteReader
While dr2.Read
Chart1.Series("Score").Points.AddXY(dr2("Month").ToString, dr2("Score").ToString) 'Adds the month/score to the graph
End While
End Sub
You can also add in If statements or error checking before running the code to make sure a selection has been made from the user.
Hth
Chicken

Turning on Option Strict will force you to use .ToString .SelectedItem is an object and Option Strict requires an explicit conversion. Not too many extra keystrokes but it could save your runtime errors.
Dim cmdd As OleDbCommand = New OleDbCommand("SELECT [Score], [Month] FROM [" & ListBox1.SelectedItem.ToString & "]", myConnection)

Laziness will do you no good. You should try to write all the table names after the FROM clause. Maybe that will solve it.

Related

select case and error join multiple table

Imports System.Data.OleDb
Public Class Form1
Dim conn As OleDbConnection
Dim cmd As OleDbCommand
Dim da As OleDbDataAdapter
Dim strSQL As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnsearch.Click
Dim fieldselect As String = ""
Select Case ComboBox1.Text
Case "startYear"
fieldselect = "startYear"
Case "genres"
fieldselect = "genres"
Case "Rating"
fieldselect = "Rating"
End Select
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Movies.accdb; Persist Security Info=False;")
strSQL = "SELECT startYear, genres, averageRating FROM (basic.tconst Inner JOIN Rating.tconst on basic.tconst=Rating.tconst)" & fieldselect & "'" & TextBox1.Text & "%'"
conn.Open()
da = New OleDbDataAdapter(strSQL, conn)
Dim ds As New DataSet("Movies")
da.Fill(ds, "Movies")
DataGridView1.DataSource = ds.Tables("Movies")
conn.Close()
End Sub
Keep you data objects local so you can control there closing and disposing. Using...End Using blocks do this for you even it there is an error.
Are all your fields in the Select Case the same datatype? If not you will have to adjust the code. If you need help, tell me the datatypes so I can fix the code.
Always use parameters to avoid sql injection. A text box can hold a Drop Table command. Parameters are treated as values not executable code.
If you need to update later in the code, you will need to have a primary key available in your Select.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Since your field name exactly matches the combo text the Case statement is not necessary
Dim fieldselect As String = ComboBox1.Text
Dim dt As New DataTable
Using conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Movies.accdb; Persist Security Info=False;")
Dim strSQL = "SELECT startYear, genres, averageRating FROM basic.tconst Inner JOIN Rating.tconst on basic.tconst=Rating.tconst Where " & fieldselect & " = #FieldValue;"
Using cmd As New OleDbCommand(strSQL, conn)
cmd.Parameters.Add("#FieldValue", OleDbType.VarChar).Value = TextBox1.Text
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
i wanted to use combo box as the filter for my program, i need to filter data from 2 different table. rating has it own table and basic is different table. both of the field mention above does not have any connection.
It's a bit had to help without context but I gave it a try :
I would replace
strSQL = "SELECT startYear, genres, averageRating FROM (basic.tconst Inner JOIN Rating.tconst on basic.tconst=Rating.tconst)" & fieldselect & "'" & TextBox1.Text & "%'"
With
"SELECT startYear, genres, averageRating " &
"FROM basic.tconst " &
"INNER JOIN Rating.tconst on basic.tconst=Rating.tconst " & fieldselect & "'" & TextBox1.Text & "%'"
To get better help, could you explain how tables Rating and basic works and what fieldselect is ?

How to take data from access data to Combobox

Public Class AdminP_Time2
Dim conn As OleDbConnection
Dim cmd As OleDbCommand
Dim sql As String
Dim dr As OleDbDataReader
Private Sub AdminP_Time2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database.accdb;Persist Security Info=False;")
conn.Open() 'opens the connection
sql = "SELECT * FROM LecturerName"
cmd = New OleDbCommand(sql, conn)
dr = cmd.ExecuteReader
If dr.Read = True Then
ComboBox1.Text = dr("LecturerName")
End If
why my combobox just show me 1 item ? can anyone help me ? i want take my access data to Combobox.
The reason that your own code doesn't work is that you're only reading one record. You need a loop, e.g.
While dr.Read()
ComboBox1.Items.Add(dr("LecturerName"))
End While
That said, your code should look more like this:
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database.accdb;Persist Security Info=False;"),
cmd As New OleDbCommand("SELECT * FROM LecturerName", conn)
conn.Open()
Using dr As OleDbDataReader = cmd.ExecuteReader()
Dim tbl As New DataTable
tbl.Load(dr)
With ComboBox1
.DisplayMember = "LecturerName"
.DataSource = tbl
End With
End Using
End Using
That will load the data into a DataTable and bind that to the ComboBox. You should also set the ValueMember of the ComboBox if you want to be able to access the PK value of the selected record via the SelectedValue of the ComboBox. You should also specify what columns you want to retrieve data from rather than using a wildcard unless you genuinely want every column.
Here is a good example.
Sub TryThis()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strSQL As String
Set db = CurrentDb
Set qdf = db.QueryDefs("qryStaffListQuery”)
strSQL = "SELECT tblStaff.* ” & _
"FROM tblStaff ” & _
"WHERE tblStaff.Office='" & Me.cboOffice.Value & "’ ” & _
"AND tblStaff.Department='" & Me.cboDepartment.Value & "’ ” & _
"AND tblStaff.Gender='" & Me.cboGender.Value & "’ ” & _
"ORDER BY tblStaff.LastName,tblStaff.FirstName;”
End Sub
You can find all details from the link below.
http://www.fontstuff.com/access/acctut17.htm

How to create a query in Visual Studio 2013 using Visual Basic

I have the following code and through debugging the problem begins at the While loop. I am trying to retrieve information from 2 tables and insert it into the table created. The information is not being inserted into the table and I am getting blank rows.
Imports System.Data.OleDb
Public Class RouteToCruise
Private Sub RouteToCruise_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Route_Btn_Click(sender As Object, e As EventArgs) Handles Route_Btn.Click
Dim row As String
Dim connectString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=M:\ICT-Group-Project\DeepBlueProject\DeepBlueProject\DeepBlueTables.mdb"
Dim cn As OleDbConnection = New OleDbConnection(connectString)
cn.Open()
Dim CruiseQuery As String = "SELECT CruiseID, RouteID FROM Cruise WHERE CruiseID =?"
Dim RouteQuery As String = "SELECT RouteName FROM Route WHERE RouteID =?"
Dim cmd As OleDbCommand = New OleDbCommand(CruiseQuery, cn)
Dim cmd2 As OleDbCommand = New OleDbCommand(RouteQuery, cn)
cmd.Parameters.AddWithValue("?", Route_Txt.Text)
Dim reader As OleDbDataReader
reader = cmd.ExecuteReader
'RCTable.Width = Unit.Percentage(90.0)
RCTable.ColumnCount = 2
RCTable.Rows.Add()
RCTable.Columns(0).Name = "CruiseID"
RCTable.Columns(1).Name = "Route"
While reader.Read()
Dim rID As String = reader("RouteID").ToString()
cmd2.Parameters.AddWithValue("?", rID)
Dim reader2 As OleDbDataReader = cmd2.ExecuteReader()
'MsgBox(reader.GetValue(0) & "," & reader.GetValue(1))
row = reader("CruiseID") & "," & reader2("RouteName")
RCTable.Rows.Add(row)
cmd.ExecuteNonQuery()
reader2.Close()
End While
reader.Close()
cn.Close()
End Sub
End Class
If I understand your tables structure well then you could just run a single query extracting data from the two table and joining them in a new table returned by the query
Dim sql = "SELECT c.CruiseID c.CruiseID & ',' & r.RouteName as Route " & _
"FROM Cruise c INNER JOIN Route r ON c.RouteID = c.RouteID " & _
" WHERE c.CruiseID = #cruiseID"
Dim cmd As OleDbCommand = New OleDbCommand(sql, cn)
cmd.Parameters.Add("#cruiseID", OleDbType.Int).Value = Convert.ToInt32(Route_Txt.Text)
Dim RCTable = new DataTable()
Dim reader = cmd.ExecuteReader()
reader.Load(RCTable)
At this point the RCTable is filled with the data coming from the two tables and selected using the Route_Txt textbox converted to an integer. If the CruiseID field is not a numeric field then you should create the parameter as of type OleDbType.VarWChar and remove the conversion to integer
Try simplifying your query.
Dim CruiseRouteQuery As String = "SELECT C.CruiseID, C.RoutID, R.Routename FROM Cruise C LEFT JOIN Route R ON C.RouteID = R.RoutID WHERE CruiseID =?"
Also, please let us know what errors you are getting.

Vb.net db issue

I'm writing a calorie counter tool for my girlfriend...
But I've run in to an issue I really cant figure out...
I have place in my script where I would wanna take some information out from my db...
The specific place in the script thats teasing, is the one that will take out data from a row called "antal" from a table called "items".
One place in my script, I call "navn" from items, and it works perfect...
This other place, it gives me the error that there isn't any data in the row!
My code looks so far like this:
Imports System.Data.OleDb
Private Sub ins_kat_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ins_kat.SelectedIndexChanged
Dim Con = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Privat\MCC\mccdb.mdb")
Con.Open()
Dim command As OleDbCommand = New OleDbCommand("SELECT * FROM items WHERE kat = '" & ins_kat.Text & "' ORDER BY id DESC", Con)
Dim read As OleDbDataReader = command.ExecuteReader()
ins_mad.Items.Clear()
While read.Read()
ins_mad.Items.Add(read.Item("navn")) '<---- This place works!!!
End While
Con.Close()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim ialt_c_counter As String
Dim ialt_c_counter_conv As Decimal
Dim ialt_c_counter_conv2 As Decimal
Dim ialt_counter As String
Dim ialt_final As Decimal
Dim Con = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Privat\MCC\mccdb.mdb")
Con.Open()
Dim command1 As OleDbCommand = New OleDbCommand("SELECT * FROM food WHERE dag = '" & stat_dag.Text & "' AND maaned = '" & stat_maaned1.Text & "' AND aar = '" & stat_aar1.Text & "'", Con)
Dim read1 As OleDbDataReader = command1.ExecuteReader()
While read1.Read()
ialt_c_counter = read1.Item("antal")
ialt_c_counter_conv = System.Convert.ToDecimal(ialt_c_counter)
Dim commandX As OleDbCommand = New OleDbCommand("SELECT * FROM items", Con)
Dim reader As OleDbDataReader = commandX.ExecuteReader()
ialt_counter = reader.Item("antal") '<--- THIS ONE is giving me the error!!
ialt_c_counter_conv2 = System.Convert.ToDecimal(ialt_counter)
ialt_final = (ialt_c_counter_conv / 100 * ialt_c_counter_conv2) + ialt_final
End While
Con.Close()
MsgBox(ialt_final)
End Sub
End Class
By now, I want a MsgBox telling me the result of my algorithm, but I don't even get that far cause of the error message...
I guess the error you see is
InvalidOperationException: Invalid attempt to read when no data is present.
You never call Read() on the OleDbDataReader called reader.
Note how you use a While loop to call Read() for read and read1, but not reader (bad variable names, btw).

Update a Single cell of a database table in VB.net

I am using MS Access Database. Now I have to update a particular cell value. Here is my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
Dim Presc As New System.Text.StringBuilder
Dim prs As String(), j As Integer
prs = Split(txtPrescription.Text, vbCrLf)
For j = 0 To prs.Length - 1
Presc.Append(prs(j))
Presc.Append(",")
Next
Try
str = Trim(lsvCase.SelectedItems(0).Text)
'MessageBox.Show(str)
Dim con As System.Data.OleDb.OleDbConnection
Dim ds As New DataSet
Dim rea As System.Data.OleDb.OleDbDataReader
con = New OleDb.OleDbConnection
Dim da As New System.Data.OleDb.OleDbDataAdapter
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source= F:\Sowmya Laptop Backups\sowdb1.accdb;"
con.Open()
Dim cmd As OleDb.OleDbCommand = con.CreateCommand
cmd.CommandText = "UPDATE Casehistory set Prescription =' " & Presc.ToString() & "'"
rea = cmd.ExecuteReader
cmd.ExecuteNonQuery()
da.FillSchema(ds, SchemaType.Mapped)
da.Update(ds, "Casehistory")
con.Close()
Catch ex As Exception
Finally
End Try
End Sub
This code updates all the cells in that column. I want to update only the particular cell having Case_ID = str
Where I have to add the WHERE clause (WHERE Case_ID = " & str & "
I would use command parameters, neater and prevents the SQL injection issue. Something like:
cmd.CommandText = "UPDATE Casehistory set Prescription =#Presc WHERE Case_ID = #CaseID"
cmd.Parameters.AddWithValue("#Presc", Presc.ToString())
cmd.Parameters.AddWithValue("#CaseID",str)
As an aside, having all this code in the button click event is less than ideal. You might want to investigate structuring your app in a more maintainable way - perhaps with a Data Layer for example.
The Where clause should be appended to the end of the OleDbCommmand.CommandText, where you define the Update statement.