Select query based on date format in access using vb.net - vb.net

I want to fetch data from a database that falls between two dates.
The code:
con1.Open()
Dim re As String = ""
Dim d1 As DateTime = DateTimePicker2.Value.ToString("dd/MM/yyyy")
Dim d2 As DateTime = DateTimePicker3.Value.ToString("dd/MM/yyyy")
Dim cmd As New OleDbCommand("Select lno,pname,mdue,ramt from Due where ddate >= '" + Convert.ToDateTime(d1) + "' and ddate<= '" + Convert.ToDateTime(d2) + "' and ramt='0'", con1)
Dim da As OleDbDataReader = cmd.ExecuteReader
While (da.Read())
re = re & " " & da("lno").ToString.PadRight(30) & " " & da("pname").ToString.PadLeft(10) & " " & da("mdue").ToString.PadLeft(10) & Chr(13)
End While
I get a data type mismatch error. The datatype for date is Date/Time only.

You are converting to string before assiging to your DateTime variables!
Try
con1.Open()
Dim re As String = ""
Dim d1 As DateTime = DateTimePicker2.Value
Dim d2 As DateTime = DateTimePicker3.Value
Dim cmd As New OleDbCommand("Select lno,pname,mdue,ramt from Due where ddate >= #" & String.Format("{0:dd/MM/yyyy}", d1) & "# and ddate<= #" & String.Format("{0:dd/MM/yyyy}", d2) & "# and ramt='0'", con1)
Dim da As OleDbDataReader = cmd.ExecuteReader
While (da.Read())
re = re & " " & da("lno").ToString.PadRight(30) & " " & da("pname").ToString.PadLeft(10) & " " & da("mdue").ToString.PadLeft(10) & Chr(13)
End While
You should also probably use & as the concatenation operator ... https://msdn.microsoft.com/en-us/library/te2585xw.aspx

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 convert the format of datetime picker and store date in mysql data base

sqlcon = New MySqlConnection
sqlcon.ConnectionString = "server=localhost;userid=root;password=soumya;database=bams;"
Dim da, da1 As MySqlDataAdapter
Dim ds, ds1 As New DataSet
Dim attendedclass, noofclass As Integer
Dim query, query1 As String
Dim yr, mon, day, yr1, mon1, day1 As Integer
yr = DateTimePicker1.Value.Year
yr1 = DateTimePicker2.Value.Year
day = DateTimePicker1.Value.Day
day1 = DateTimePicker2.Value.Day
mon = DateTimePicker1.Value.Month
mon1 = DateTimePicker2.Value.Month
sqlcon.Open()
query1 = "select * from attendence_master where ( REGISTER_NO='" & TextBox1.Text & "' ) and ( SUBJECT='" & ComboBox1.SelectedItem.ToString() & "' ) and ( LECTURER_NAME='" & TextBox4.Text & "' ) and ( CLASS ='" & ComboBox2.SelectedItem.ToString() & "' ) and ( DAY between " & day & " and " & day1 & ") and ( MONTH between " & mon & " and " & mon1 & " ) and (YEAR between " & yr & " and " & yr1 & ")"
sqlcom = New MySqlCommand(query1, sqlcon)
da1 = New MySqlDataAdapter(sqlcom)
da1.Fill(ds1)
noofclass = ds1.Tables(0).Rows.Count()
query = "select * from attendence_master where ( REGISTER_NO='" & TextBox1.Text & "') and ( SUBJECT='" & ComboBox1.SelectedItem.text & "' ) and ( LECTURER_NAME='" & TextBox4.Text & "' ) and ( ATTENDENCE='P' ) and ( CLASS ='" & ComboBox2.SelectedItem.ToString() & "' ) and ( DAY between " & day & " and " & day1 & ") and ( MONTH between " & mon & " and " & mon1 & " ) and (YEAR between " & yr & " and " & yr1 & ")"
sqlcom = New MySqlCommand(query, sqlcon)
da = New MySqlDataAdapter(sqlcom)
da.Fill(ds)
attendedclass = ds.Tables(0).Rows.Count()
DataGridView1.DataSource = ds
sqlcon.Close()
i cannot store date in mysql data base , cz i cld nt convert the format of datetimepicker n vb , . now i hve split the values of dtpicker and stored it as integer n data base ,.. need help to execute the query .. help plz .. ty
replace this query and check. In your query you used fields day,month and year are keywords, so add brackets with that table fields in the where clause and check
sqlcon = New MySqlConnection
sqlcon.ConnectionString = "server=localhost;userid=root;password=soumya;database=bams;"
Dim da, da1 As MySqlDataAdapter
Dim ds, ds1 As New DataSet
Dim attendedclass, noofclass As Integer
Dim query, query1 As String
Dim yr, mon, day, yr1, mon1, day1 As Integer
yr = DateTimePicker1.Value.Year
yr1 = DateTimePicker2.Value.Year
day = DateTimePicker1.Value.Day
day1 = DateTimePicker2.Value.Day
mon = DateTimePicker1.Value.Month
mon1 = DateTimePicker2.Value.Month
sqlcon.Open()
query1 = "select * from attendence_master where ( REGISTER_NO='" & TextBox1.Text & "' ) and ( SUBJECT='" & ComboBox1.SelectedText.ToString() & "' ) and ( LECTURER_NAME='" & TextBox4.Text & "' ) and ( CLASS ='" & ComboBox2.SelectedText.ToString() & "' ) and ( `DAY` between " & day & " and " & day1 & ") and ( `MONTH` between " & mon & " and " & mon1 & " ) and (`YEAR` between " & yr & " and " & yr1 & ")"
sqlcom = New MySqlCommand(query1, sqlcon)
da1 = New MySqlDataAdapter(sqlcom)
da1.Fill(ds1)
noofclass = ds1.Tables(0).Rows.Count()
query = "select * from attendence_master where ( REGISTER_NO='" & TextBox1.Text & "') and ( SUBJECT='" & ComboBox1.SelectedText.text & "' ) and ( LECTURER_NAME='" & TextBox4.Text & "' ) and ( ATTENDENCE='P' ) and ( CLASS ='" & ComboBox2.SelectedText.ToString() & "' ) and ( `DAY` between " & day & " and " & day1 & ") and ( `MONTH` between " & mon & " and " & mon1 & " ) and (`YEAR` between " & yr & " and " & yr1 & ")"
sqlcom = New MySqlCommand(query, sqlcon)
da = New MySqlDataAdapter(sqlcom)
da.Fill(ds)
attendedclass = ds.Tables(0).Rows.Count()
DataGridView1.DataSource = ds
sqlcon.Close()

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"

IndexOutOfRangeException vb.net

Private Sub Button73_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button73.Click
Dim serienaam
Dim oud
Dim aantal As Integer
Dim tt
Dim bedrag As Integer
Dim totaal As Integer
serienaam = ComboBox1.SelectedItem
oud = ComboBox2.SelectedItem
aantal = TextBox7.Text
tt = "" & serienaam & " " & oud & " " & aantal & " "
cmd = New SqlCommand("SELECT '" & oud & "' FROM series Where naamserie = '" & serienaam & "' ", con)
Dim sdr As SqlDataReader = cmd.ExecuteReader()
If sdr.Read = True Then
Dim week = sdr.Item(" '" & oud & "' ") '\\gives a IndexOutOfRangeException...
bedrag = week
totaal = totaal + bedrag * aantal
sdr.Close()
'Label14.Text = totaal
ListBox1.Items.Add(tt)
End If
End Sub
When I run this it gives a IndexOutOfRangeException on
If sdr.Read = True Then
Dim week = sdr.Item(" '" & oud & "' ") \|/<---\|/gives a IndexOutOfRangeException...
bedrag = week
totaal = totaal + bedrag * aantal
Right, I'll try to answer this in an understandable fashion.
The main issue is your SQL query.
New SqlCommand("SELECT '" & oud & "' FROM series ...
What your query will look like is this. Oud will in this example be "ID":
SELECT 'ID' FROM series...
What you are telling the database is this:
For each row you can find send back the string 'ID'.
What you really want is this, notice the lack of apostrophes:
SELECT ID FROM series...
This will return the value in the Column named ID.
Run this query in this link and you'll understand better: http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all
SELECT 'CustomerID', CustomerID FROM Customers;
As a bonus, code that I believe will work. Just put it in the same place as before.
Dim oud as String
oud = ComboBox2.SelectedItem.ToString()
cmd = New SqlCommand("SELECT " & oud & " FROM series Where naamserie = '" & serienaam & "' ", con)
Dim week = sdr.Item(oud) 'As rinukkusu said
I don't think you need to quote the column name at:
Dim week = sdr.Item(oud)

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)