Searching multiple tables in Access vb.net - sql

I have a search button which looks up for data only in tblDopage but there is a field strMatrice in this table that is linked to table tblMatrice. So if the user is searching for Matrice I should retrieve Matrice from tblMatrice and innerjoin it with tblDopage on strMatrice, it's like a search inside search and the result of searching for matrice is more than 1 result so that I have many results which i should link them with tblDopage to display the final result. What shall i do, I spended 3 days searching for a solution.
I retrieved strMatrice from tblMatrice and populated a dataset with the result but I don't know how to innerjoin between a dataset and table in the database which is the tblDopage
Help is very appreciated, Thank you in advance
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Marwan_Albanna\Desktop\Autocontrol.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim sql = "SELECT * from tblDopages WHERE "
cmd = New OleDbCommand(Sql, myConnection)
Dim da As OleDbDataAdapter
If CKBrefech.Checked = True Then
sql = sql & "strRefEch = '" & TBrefech.Text & "' AND "
End If
If CKBmethode.Checked = True Then
sql = sql & "strMethode = '" & CBmethode.Text & "' AND "
End If
If CKBpurif.Checked Then
sql = sql & "strPurif = '" & CBpurif.Text & "' AND "
End If
If CKBmatrice.Checked Then
sql = sql & "strMatrice = '" & CBmatrice.Text & "' AND "
End If
If CKBmol.Checked Then
sql = sql & "strMolecule = '" & CBmol.Text & "' AND "
End If
If CKBechprep.Checked Then
sql = sql & "datDatePrepa >= #DatPrepa AND "
cmd.Parameters.Add("#DatPrepa", OleDbType.Date).Value = DTPechprep.Value.Date
End If
If CKBechau.Checked Then
sql = sql & "datDatePrepa <= #Datau AND "
cmd.Parameters.Add("#Datau", OleDbType.Date).Value = DTPechau.Value.Date
End If
If CKBtrigprepa.Checked = True Then
sql = sql & "strTrigPrepa = '" & TBtrigprepa.Text & "' AND "
End If
If CKBtriganaly.Checked = True Then
sql = sql & "strTrigAnaly = '" & TBtrigAnaly.Text & "' AND "
End If
If CKBappar.Checked = True Then
sql = sql & "strNomTech = '" & CBappar.Text & "' AND "
End If
If CKBnumappar.Checked = True Then
sql = sql & "[strEquip(Appareil)] = '" & CBnumappar.Text & "' AND "
End If
If CKBteneurmini.Checked = True Then
sql = sql & "dblDopage >= " & TBteneurmini.Text & " AND "
End If
If CKBteneurmax.Checked = True Then
sql = sql & "dblDopage <= " & TBteneurmax.Text & " AND "
End If
'if referentiel is enabled
myConnection.Close()
If CKBnomref.Checked Then
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Marwan_Albanna\Desktop\Autocontrol.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
'Get IDref from table tblRefMatDetails and then make an innerjoin with tblRefMatrice to retrieve the matrice and insert it into the search query of tblDopages
Dim query = "select distinct a.strMatrice from tblRefMatrice a INNER JOIN tblRefMatDetails b on a.intIDref=b.intIDRef where "
cmd = New OleDbCommand(query, myConnection)
Try
If CKBnomref.Checked Then
query = query & "b.strReferentiel = '" & CBnomref.Text & "' AND "
End If
If CKBniv1.Checked Then
query = query & "b.strNIveau1 = '" & CBniv1.Text & "' AND "
End If
If CKBniv2.Checked Then
query = query & "b.strNiveau2 = '" & CBniv2.Text & "' AND "
End If
If CKBniv3.Checked Then
query = query & "b.strNiveau3 = '" & CBniv3.Text & "' AND "
End If
If CKBniv4.Checked Then
query = query & "b.strNiveau4 = '" & CBniv4.Text & "' AND "
End If
' Remove the last AND if any ....'
If query.EndsWith(" AND ") Then
query = query.Substring(0, query.Length - 4)
End If
' Remove the WHERE if no textbox has been filled....'
If query.EndsWith(" WHERE ") Then
query = query.Substring(0, query.Length - 7)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
cmd.CommandText = query
cmd.Connection = myConnection
Dim MyDataTable As New DataTable
Dim da As New OleDbDataAdapter(query, myConnection)
da.Fill(MyDataTable)
Dim row As DataRow
For Each row In MyDataTable.Rows
Dim strMatrice As String
strMatrice = row("strMatrice")
Next row
DataGridView2.DataSource = MyDataTable
'to focus on first row of DGV after populating it
DataGridView2.Rows(0).Selected = True
myConnection.Close()
Dim matrice As String
For x As Integer = 0 To DataGridView2.Rows.Count - 2
matrice = DataGridView2.Rows(x).Cells(0).Value
sql = sql & " strMatrice = '" & matrice.ToString & "' AND "
Dim row As DataRow
For Each row As DataRow In MyDataTable.Rows
matrice = row.Item("Detail")
Next row
Next
End If
' Remove the last AND if any ....'
If sql.EndsWith(" AND ") Then
sql = sql.Substring(0, sql.Length - 4)
End If
' Remove the WHERE if no textbox has been filled....'
If sql.EndsWith(" WHERE ") Then
sql = sql.Substring(0, sql.Length - 7)
End If
' cmd = New OleDbCommand(sql, myConnection)
cmd.CommandText = sql
cmd.Connection = myConnection
Dim MyDataSet As New DataSet
da = New OleDbDataAdapter(sql, myConnection)
da.SelectCommand = cmd
da.SelectCommand.Parameters.Add(New OleDbParameter("#DatPrepa", DTPechprep.Value)) 'adding date parameters to datatable
da.SelectCommand.Parameters.Add(New OleDbParameter("#datau", DTPechprep.Value)) 'adding date parameters to datatable
'da.SelectCommand.Parameters.Add(New OleDbParameter("#Matrice", matrice.ToString)) 'adding Matrice parameters to datatable
da.Fill(MyDataSet, "Matrice")
DataGridView1.DataSource = MyDataSet.Tables("Matrice")
'to focus on first row of DGV after populating it
DataGridView1.Rows(0).Selected = True
LBnumresult.Text = DataGridView1.RowCount - 1

Related

VB.net Load(cmd.ExecuteReader)

I have a function which i am getting syntax Error which I am using the same copy in other without any error .I am trying to open an Access table and read line by line and do some updates on it .
Function FlattenTable(Current As String, Freezefrom As Date, DateRef As Date, db As String)
Dim date1 As Date
Dim sql1 As String
Dim FreezeHrs As Double
Dim FreezeLnds As Long
Dim rs1 As DataTable
Dim cmd As OleDb.OleDbCommand
Dim con As New OleDb.OleDbConnection With {
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & db
}
con.Open()
If Freezefrom > DateRef Then
date1 = Freezefrom
Else
date1 = DateRef
End If
sql1 = "SELECT * FROM [Hours & Landings & Cycles] WHERE [A/C] = '" & Current & "' [DATE]= " & date1 & ""
cmd = New OleDbCommand(sql1, con)
rs1 = New DataTable
rs1.Load(cmd.ExecuteReader)
FreezeHrs = rs1.Rows.Item(0).Item(3)
FreezeLnds = rs1.Rows.Item(0).Item(4)
' "UPDATE [Hours & Landings & Cycles] SET [Code] = 'X' WHERE [A/C] = '" & Current & "' AND [Date]>=" & ActualEIS & " AND [Date]<=#" & DateValue(Format("{0:MM/dd/yyyy}", EndDate)) & "#"
sql1 = "UPDATE [Hours & Landings & Cycles] SET [HRS] = '" & FreezeHrs & "' WHERE [A/C] = '" & Current & "' AND [DATE]>='" & date1 & "'"
cmd = New OleDbCommand(sql1, con)
cmd.ExecuteNonQuery()
End Function
rs1.Load(cmd.ExecuteReader) is a data table reader

How to insert looping data in Oracle Database using VB.NET

Dim cmd = New OracleCommand
For i = 0 To DataGridView1.Rows.Count - 1
Sql = "INSERT INTO TM_EMPLOYEE_INFO (V_EMPLOYEE_NO, "
Sql = Sql & "V_NAME_TRAINEE,N_GENDER,V_COMPANY) "
Sql = Sql & " VALUES('" & DataGridView1.Rows(i).Cells(0).Value & "', "
Sql = Sql & "'" & DataGridView1.Rows(i).Cells(1).Value & "', "
Sql = Sql & "'" & DataGridView1.Rows(i).Cells(2).Value & "', "
Sql = Sql & "'" & DataGridView1.Rows(i).Cells(3).Value & "') "
Next
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Using connection As New OracleConnection("Provider=OraOLEDB.Oracle;Data Source = XE;User ID = MAN_HOUR;Password = FDTP_MAN_HOUR;")
Dim command As New OracleCommand(Sql)
command.Connection = connection
Try
connection.Open()
command.ExecuteNonQuery()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
This is my code. I thinks its already okay but when I run the program the vshost.exe message box appeared. Please help me. Thank you very much.
When you use provider OraOLEDB.Oracle you must use OleDbConnection and OleDbCommand. Otherwise you have to use provider Oracle.DataAccess.
Then you must execute the insert inside the loop, not outside. Would be like this:
Using connection As New OleDbConnection("Provider=OraOLEDB.Oracle;Data Source = XE;User ID = MAN_HOUR;Password = FDTP_MAN_HOUR;")
connection.Open()
Dim command As New OleDbCommand()
command.CommandType = CommandType.Text
command.Connection = connection
For i = 0 To DataGridView1.Rows.Count - 1
Sql = "INSERT INTO TM_EMPLOYEE_INFO (V_EMPLOYEE_NO, "
Sql = Sql & "V_NAME_TRAINEE,N_GENDER,V_COMPANY) "
Sql = Sql & " VALUES('" & DataGridView1.Rows(i).Cells(0).Value & "', "
Sql = Sql & "'" & DataGridView1.Rows(i).Cells(1).Value & "', "
Sql = Sql & "'" & DataGridView1.Rows(i).Cells(2).Value & "', "
Sql = Sql & "'" & DataGridView1.Rows(i).Cells(3).Value & "') "
command.CommandText = Sql
Try
command.ExecuteNonQuery()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Next
connection.Close()
End Using
However, this is a bad implementation, better work with bind variables like this:
Using connection As New OleDbConnection("Provider=OraOLEDB.Oracle;Data Source = XE;User ID = MAN_HOUR;Password = FDTP_MAN_HOUR;")
connection.Open()
Dim command As New OleDbCommand()
command.CommandType = CommandType.Text
command.Connection = connection
Sql = "INSERT INTO TM_EMPLOYEE_INFO "
Sql = Sql & "(V_EMPLOYEE_NO, V_NAME_TRAINEE,N_GENDER,V_COMPANY) "
Sql = Sql & "VALUES (?,?,?,?)"
command.CommandText = Sql
command.Parameters.Add("empNo", OleDbType.Integer)
command.Parameters.Add("trainee", OleDbType.VarChar, 100)
command.Parameters.Add("gender", OleDbType.VarChar, 10)
command.Parameters.Add("company", OleDbType.VarChar, 100)
For i = 0 To DataGridView1.Rows.Count - 1
For c = 0 To 4
command.Parameters(c).Value = DataGridView1.Rows(i).Cells(c).Value
Next
Try
command.ExecuteNonQuery()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Next
connection.Close()
End Using

An expression of non-boolean type specified in a context where a condition is expected, near 'and'

I have converted my database from Access to Sql as Sql didn't accept format() so is displaying an error.
This is my code:
DefaultStr = "" &
"SELECT StudentAccount.Dated, StudentAccountS.StAdmNo, StudentAccountS.StClass, " &
"StudentAccountS.StName, StudentAccount.Perticular, StudentAccount.Amount,StudentAccount.Remark,StudentAccount.PayMode,TransactionID " &
"FROM (StudentAccount LEFT OUTER JOIN StudentAccountS ON StudentAccount.SSID = StudentAccountS.SSID) " &
"WHERE (StudentAccount.Debit) and (StudentAccount.Dated Between " &
"#" & Format(DateFrom, "MM/dd/yyyy") & "# AND #" & Format(DateTo, "MM/dd/yyyy") & "#)"
Select Case SIndex
Case 0
SelStr = " AND (StudentAccount.PayMode = '" & OptionStr & "') Order By StudentAccount.Dated"
Case 1
SelStr = " AND (StudentAccount.Perticular = '" & OptionStr & "') Order By StudentAccount.Dated"
Case 2, 3
SelStr = " AND (StudentAccount.TransType = '" & filterStr & "') Order By StudentAccount.Dated"
Case Else
SelStr = Nothing
End Select
Da = New SqlDataAdapter(DefaultStr & SelStr, Conn)
Ds = New DataSet
Da.Fill(Ds)
You have to use something like this:
Dim CMD As SqlClient.SqlCommand = Conn.CreateCommand
Dim dtStart As DateTime = New DateTime(2015, 9, 6, 10, 1, 0)
Dim dtEnd As DateTime = New DateTime(2015, 9, 6, 11, 0, 0)
CMD.CommandText = "SELECT * FROM Table1 WHERE Date BETWEEN '" & dtStart.ToString("yyyy-MM-dd HH:mm:ss") & "' AND '" & _
dtEnd.ToString("yyyy-MM-dd HH:mm:ss") & "'"
Dim DA As New SqlClient.SqlDataAdapter
DA.SelectCommand = CMD
Dim DT As New DataTable
DA.Fill(DT)
Howewer i suggest you to start learing SqlParameter for queries (that are much more reliable, as for example in dealing with sql injection). Simply use something like that:
CMD.Parameters.Add("#DateStart", SqlDbType.DateTime2, 20).Value = dtStart
CMD.Parameters.Add("#DateEnd", SqlDbType.DateTime2, 20).Value = dtEnd
CMD.CommandText = "SELECT * FROM Table1 WHERE Date BETWEEN #DateStart AND #DateEnd"

Auto refresh DataGridView after update

I want to get auto refresh Datagridview after update
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim CON As SqlConnection
CON = New SqlConnection("Data Source=.;Initial Catalog=PantienDatabase;Integrated Security=True")
CON.Open()
Try
cmd = New SqlCommand
cmd.Connection = CON
cmd.CommandText = "UPDATE Patient_Detail SET Name ='" & TextBoxName.Text & "',Age = '" & TextBoxAge.Text & "',Sex = '" & TextBoxSex.Text & "',Address = '" & TextBoxAddress.Text & "',Check_In = '" & TextBoxCHiN.Text & "',Check_In_Illness = '" & TextBoxCHinL.Text & "',Sevice = '" & TextBoxService.Text & "',Check_out_Illness = '" & TextBoxCHoutL.Text & "',Check_out = '" & TextBoxCHout.Text & "',Transfer = '" & TextBoxTransfer.Text & "',Patient_result = '" & ComboBoxPtr.Text & "' WHERE ID = '" & TextBoxid.Text & "' "
//'cmd.CommandText = "UPDATE Patient_Detail SET Name = #Name, Age = #Age, Sex = #Sex, Address = #Address, Check_In = #Check_In, Check_In_Illness =#Check_in_illness, Sevice =#Service, Check_out_Illness =#Check_out_Illness, Check_out = #Check_out ,Transfer = #Transfer, Patient_result = #Pantient_result WHERE ID = #ID '
cmd.ExecuteNonQuery()
DataGridView1.Refresh()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
In this case you need to rebind the data in DataGridView Like :
Dim conn As New MySqlConnection(My.Settings.myConn)
Dim da As New MySqlDataAdapter
Dim ds As New DataSet
Dim str1 As String = "select * from Patient_Detail "
da.SelectCommand = New MySqlCommand(str1, conn)
da.Fill(ds)
conn.Close()
DataGridView1.DataSource = ds.Tables(0)

Dynamically Add Fields in Access Saved Query

I have a ComboBox named ComboBox_Calculations in my program that is filled with calculations (ex. Current_Ratio, Total_Debt_To_Assets_Ratio). ComboBox_Calculations is actually populated by using the contents of a field in a tabled called Criteria in my Access Database.
I need to create a saved query called Calculations_Quarterly. The query needs to have fields of Ticker, [Year], Period and then one field for every item in ComboBox_Calculations. So for this example I would also need fields named Current_Ratio and Total_Debt_To_Assets_Ratio.
Here is what my tables look like so far:
Criteria
Calculations_Quarterly
Here is the code I have that adds one field at a time (in this case Current_Ratio. But I do not know how add a column for every item in ComboBox_Calculations
con.Open()
Dim dr As OleDbDataReader
Dim cmd6 As New OleDb.OleDbCommand("SELECT Calculation, [Interval], Formula FROM Criteria", con)
dr = cmd6.ExecuteReader
dr.Read()
Dim Calculation = dr("Calculation").ToString
Dim Interval = dr("Interval").ToString
Dim Formula = dr("Formula").ToString
Dim Where_Statement As String
If Interval = "Daily" Then
Where_Statement = "WHERE Historical_Stock_Prices.[Date] < " & DateTime.Now.Date & ""
ElseIf Interval = "MRQ" Then
Where_Statement = "WHERE Income_Statements.Period < 5"
ElseIf Interval = "TTM" Then
Where_Statement = "WHERE Income_Statements.Period < 5"
ElseIf Interval = "5 Year" Then
Where_Statement = "WHERE Income_Statements.Period = 5"
Else
Where_Statement = ""
End If
Try
Dim cmd2 As OleDbCommand = New OleDbCommand("CREATE PROC " & Calculation & " AS SELECT Income_Statements.Ticker, Income_Statements.[Year], Income_Statements.Period, " & Formula & " AS " & Calculation & " FROM Income_Statements INNER JOIN Balance_Sheets ON (Income_Statements.Ticker = Balance_Sheets.Ticker) AND (Income_Statements.[Year] = Balance_Sheets.[Year]) AND (Income_Statements.Period = Balance_Sheets.Period)" & Where_Statement & "", con)
cmd2.ExecuteNonQuery()
Catch ex As Exception
Finally
Dim cmd2a As OleDbCommand = New OleDbCommand("DROP PROCEDURE " & Calculation & "", con)
cmd2a.ExecuteNonQuery()
Dim cmd2b As OleDbCommand = New OleDbCommand("CREATE PROC " & Calculation & " AS SELECT Income_Statements.Ticker, Income_Statements.[Year], Income_Statements.Period, " & Formula & " AS " & Calculation & " FROM Income_Statements INNER JOIN Balance_Sheets ON (Income_Statements.Ticker = Balance_Sheets.Ticker) AND (Income_Statements.[Year] = Balance_Sheets.[Year]) AND (Income_Statements.Period = Balance_Sheets.Period)" & Where_Statement & "", con)
cmd2b.ExecuteNonQuery()
End Try
con.Close
I couldnt find the name of you combobox or how it is filled so assuming it is named Combo1, and you filled it using Combo1.Items.Add("..."), you would want something like this:
Dim sb as new System.Text.StringBuilder("")
For each s as string in Combo1.Items
sb.Append("," & s)
Next
And then in your SQL:
Dim cmd2 As OleDbCommand = New OleDbCommand("CREATE PROC " & Calculation & " AS SELECT Income_Statements.Ticker, Income_Statements.[Year], Income_Statements.Period, " & Formula & " AS " & Calculation & sb.ToString & " FROM Income_Statements INNER JOIN Balance_Sheets ON (Income_Statements.Ticker = Balance_Sheets.Ticker) AND (Income_Statements.[Year] = Balance_Sheets.[Year]) AND (Income_Statements.Period = Balance_Sheets.Period)" & Where_Statement & "", con)