Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
If R2.Checked Then
da = New OleDbDataAdapter("Select * from [maint] where
[centrale]='" & centralev.Text & "' ", MyConn) 'Change items to your
database name
End If
If R1.Checked Then
da = New OleDbDataAdapter("Select * from [maint] where
datevisite='" & dateintervention.Value.ToShortDateString() & "' ",
MyConn) 'Change items to your database name
End If
da.Fill(ds, "maint") 'Change items to your database name
Dim view As New DataView(tables(0))
source1.DataSource = view
DGV.DataSource = view
End Sub
End Class
I used 2 buttonradio to select criteria of search , I have problem with date search, Data type mismatch in criteria expression.
try to change
incorrect
da = New OleDbDataAdapter("Select * from [maint] where
datevisite='" & dateintervention.Value.ToShortDateString() & "' ",
MyConn) 'Change items to your database name
correct
da = New OleDbDataAdapter("Select * from [maint] where
datevisite='" & dateintervention.Value.ToString("yyyy-MM-dd") & "' ",
MyConn) 'Change items to your database name
Example for format
Expanding on Plutonix comment to your question you can try:
Dim cmd = New OleDbCommand("Select * from [maint] where datevisite = ?")
Dim param = New OleDbParameter("#datevisite", OleDbType.Date)
param.Value = dateintervention.Value
cmd.Parameters.Add(param)
da = New OleDbDataAdapter (cmd, MyConn)
In this way ADO.NET will take care for you to replace the question mark in the query text with the proper date value formatted as required by OleDb syntax. You entirely avoid string concatenation errors and you don't need to learn any formatting rule for all available OleDb data types.
Besides it should be safer.
Related
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 ?
I was wondering how I could change the code below, to allow me to search for the most recent record. I am creating a Hotel Booking System and want to use the most recent price in the database but at the moment, it is just searching using the labels which I don't want.
Dim str1 As String
Dim dbpassword As String = "123"
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= E:\Computing\Hotel Booking System\Database\Hotel Booking System.accdb ;Jet OLEDB:Database Password =" & dbpassword & ";"
Dim MyConn As OleDbConnection
Dim dr As OleDbDataReader
Private Sub Information_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim PriceFound As String = False
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
MyConn.Open()
str1 = ("SELECT * FROM [Prices] WHERE [Adult] = '" & LblPriceAdult.Text & "' AND [Child] = '" & LblPriceChild.Text & "'")
Dim cmd1 As OleDbCommand = New OleDbCommand(str1, MyConn)
dr = cmd1.ExecuteReader
While dr.Read()
PriceFound = True
DateDisplay = dr("ID").ToString
AdultPrice = dr("Adult").ToString
ChildPrice = dr("Child").ToString
SingleRoom = dr("Single").ToString
DoubleRoom = dr("Double").ToString
FamilyRoom = dr("Family").ToString
If PriceFound = True Then
LblPriceAdult.Text = AdultPrice
LblPriceChild.Text = ChildPrice
LblPriceDoubleRoom.Text = DoubleRoom
LblPriceFamilyRoom.Text = FamilyRoom
LblPriceSingleRoom.Text = SingleRoom
End If
End While
MyConn.Close()
End Sub
Based on your previous comments, you need to rewrite your SQL to trap the most recent record.
Try something like this:
SELECT MAX(ID) FROM [Prices] ORDER BY ID DESC
I tried the answer above. However for the code above, it wouldn't search for the most recent so I changed DESC to ASC
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.
I am trying to return rows in a listbox from a sql database. I only want the rows to be returned where 3 fields match textbox values. Currently, the listbox is returning ALL rows if ANYTHING is typed into any of the 3 textboxes. If nothing is typed in , nothing shows up (that part is the expected/correct behavior).
My code is:
Private Sub tireselect_Load(sender As Object, e As EventArgs) Handles MyBase.Load
m_cn.ConnectionString = "Data Source=localhost;Initial Catalog=tires;Integrated Security=True"
m_cn.Open()
'Dim con As New SqlConnection()
'Dim cmd As String = "Select brand, model, width, aspect, rim, retail from dbo.tires"
Dim sqltext = "SELECT [ID] ,[brand] ,[model] ,[cost] ,[retail] ,[width] ,[aspect] ,[rim] FROM [tires].[dbo].[tires]"
Using sqlCon = New SqlConnection("Data Source=localhost;Initial Catalog=tires;Integrated Security=True")
sqlCon.Open()
Dim cmd = New SqlCommand(sqltext, sqlCon)
cmd.Parameters.AddWithValue("#tirewidth", (Int(TireLookup.txtWidth.Text)))
cmd.Parameters.AddWithValue("#tireaspect", (Int(TireLookup.txtAspect.Text)))
cmd.Parameters.AddWithValue("#tirerim", (Int(TireLookup.txtRim.Text)))
cmd.ExecuteNonQuery()
End Using
Dim m_da As New SqlDataAdapter("SELECT [ID] ,[brand] ,[model] ,[cost] ,[retail] ,[width] ,[aspect] ,[rim] FROM [tires].[dbo].[tires] where [width]=tirelookup.txtwidth.text AND [aspect]=tirelookup.txtwidth.text AND [rim]=tirelookup.txtrim.text", m_cn)
Dim myDataSet As New DataSet()
m_da.Fill(myDataSet, "dbo.tires")
Dim myDataTable As DataTable = myDataSet.Tables(0)
Dim tempRow As DataRow
For Each tempRow In myDataTable.Rows
ListBox1.Items.Add(tempRow("brand"))
ListBox2.Items.Add(tempRow("model"))
ListBox3.Items.Add(tempRow("width") & " / " & tempRow("aspect") & " / " & tempRow("rim"))
ListBox4.Items.Add("$ " & tempRow("retail") & " Tire ID=" & (tempRow("ID") - 1))
Next
End Sub
You need to change your predicates like this:
where [width]=#tirewidth
AND [aspect]=#tireaspect
AND [rim]=#tirerim
Hi i need to populate a combobox using the selected value in another combo. The coding that i use doesn't produce the required output. i have an excel sheet with columns called "BaseStation" & "SectorID". Combobox2 must display the related sector id with respect to the selected BaseStation
Given below is the error that i get:
"Syntax error (missing operator) in query expression 'BaseStation='."
Please help. the coding given below:
Private Sub ComboBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.TextChanged
Using cn As New OleDb.OleDbConnection With _
{ _
.ConnectionString = _
<S>
provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\WalkAir Customers.xls;
Extended Properties="Excel 8.0; HDR=Yes;"
</S>.Value _
}
Dim cmd As New OleDb.OleDbCommand
Dim dr As System.Data.IDataReader
cn.Open()
cmd = New OleDb.OleDbCommand()
cmd.Connection = cn
cmd.CommandText = "SELECT * FROM [Sheet1$] WHERE BaseStation=" & ComboBox1.Text
Dim dtData As New DataTable
dr = cmd.ExecuteReader
dtData.Load(dr)
dtData.Columns("SectorID").ColumnMapping = MappingType.Hidden
bsCustomers.DataSource = dtData
End Using
ComboBox2.DisplayMember = "SectorID"
ComboBox2.DataSource = bsCustomers
End Sub
Try putting single quotes around the BaseStation parameter:
cmd.CommandText = "SELECT * FROM [Sheet1$] WHERE BaseStation='" & ComboBox1.Text & "'"