I have this code
Dim conex As SqlConnection = New SqlConnection(conxst)
Dim caixa As Integer = ComboBox1.SelectedItem
Dim verdat As Date = DateTimePicker1.Text
Dim verdat1 As Date = "05/07/2012"
conex.Open()
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da As New SqlDataAdapter("select codigo,data,horario from alteraca where data = '" & verdat1 & "' ", conex)
da.Fill(dt)
this code work when verdat1 is in the format "mm/dd/yyyy" , how i convert the date from mine datetimepicker (dd/mm/yyyy) to the format "mm/dd/yyyy" to place in the statment??? Thanks.
You shouldn't use string representation of a value when you already have binary representation.
Dim dt As New DataTable
Using conex As New SqlConnection(conxst)
conex.Open()
Using cmd As New SqlCommand("select codigo, data, horario from alteraca where data = #data", conex)
cmd.Parameters.AddWithValue("#data", DateTimePicker1.Value)
Using da As New SqlDataAdapter(cmd)
da.Fill(dt)
End Using
End Using
End Using
With
verdat1.ToString("MM/dd/yyyy")
You can select how the date is converted to a string.
Also, you can set the dateTimePicker Custom Format as you wish :
dateTimePicker1.Format = DateTimePickerFormat.Custom
dateTimePicker1.CustomFormat = "MM/dd/yyyy"
In sql query
-use to_date to convert String to date
-and to char for reverse
In your case
select codigo,data,horario from alteraca where data = to_date('" & verdat1 & "','dd/mm/yyyy') ", conex
here 'dd/mm/yyyy' is format of your variable...
Actually, a better (and safer way) to do the query is to use Parameters and Using statements. The Using statement automatically closes the connection, commands and adapter.
Dim caixa As Integer = ComboBox1.SelectedItem
Dim verdat As Date = DateTimePicker1.Text
Dim verdat1 As Date = "05/07/2012"
Dim ds As New DataSet
Dim dt As New DataTable
Using conex as New SQLConnection(conxst)
conex.Open()
Using cmdex as New SQLCommand("select codigo,data,horario from alteraca where data = #DATE " , conxst)
cmdex.Parameters.AddWithValue("#DATE",verdat1)
Using da As New SqlDataAdapter(cmdex)
da.Fill(dt)
End Using
End Using
End Using
You can convert the date like this:
verdat1.ToString("MM/dd/yyyy")
you can use DateTimePicker1.value. It is easily solve
Related
Dim query As String = "select * from mytable where strftime('%Y-%m-%d',tarih) between 'TextBox4.text' and 'TextBox5.text' "
Can not assign query variable ?
Datagridview result = empty
info :Datagridview date format = 2018-01-01 17:42:24
Dim btarihyil As String
btarihyil = DateTimePicker2.Value.ToString.Substring(6, 4)
Dim btarihay As String
btarihay = DateTimePicker2.Value.ToString.Substring(3, 2)
Dim btarihgun As String
btarihgun = DateTimePicker2.Value.ToString.Substring(0, 2)
TextBox4.Text = btarihyil & "-" & btarihay & "-" & btarihgun
Dim bttarihyil As String
bttarihyil = DateTimePicker3.Value.ToString.Substring(6, 4)
Dim bttarihay As String
bttarihay = DateTimePicker3.Value.ToString.Substring(3, 2)
Dim bttarihgun As String
bttarihgun = DateTimePicker3.Value.ToString.Substring(0, 2)
TextBox4.Text = btarihyil & "-" & btarihay & "-" & btarihgun
TextBox5.Text = bttarihyil & "-" & bttarihay & "-" & bttarihgun
Dim Yol As String = "Data Source=database1.s3db;version=3;new=False"
Using MyConn As New SQLiteConnection(Yol)
If (MyConn.State = ConnectionState.Closed) Then
MyConn.Open()
End If
Dim Sorgu As String = "select * from mytable where strftime('%Y-%m-%d',tarih) between 'TextBox4.text' and 'TextBox5.text' "
Using MyCmd As New SQLiteCommand(Sorgu, MyConn)
Dim Da As New SQLiteDataAdapter(MyCmd)
Dim Ds As New DataSet
Dim Dt As New DataTable
Ds.Reset()
Da.Fill(Ds)
Dt = Ds.Tables(0)
Dim Bs As New BindingSource With {.DataSource = Dt}
DataGridView1.DataSource = Bs
Bs.MoveLast()
MyConn.Close()
MyCmd.Dispose()
MyConn.Dispose()
End Using
End Using
End Sub
You are using "TextBox4.Text" and "TextBox5.Text" literally in the query. That will not pass the values of textboxes to the query. So it will result in error.
Also you need to use parameterized query to avoid syntax errors.
Also I am not sure why you are using strftime function. That function is used just for formatting.
Following the code I re-written using parameterzied query approach.
Dim Yol As String = "Data Source=database1.s3db;version=3;new=False"
Using MyConn As New SQLiteConnection(Yol)
If (MyConn.State = ConnectionState.Closed) Then
MyConn.Open()
End If
Dim Sorgu As String = "select * from mytable where tarih between #startDate and #endDate "
Using MyCmd As New SQLiteCommand(Sorgu, MyConn)
Dim startDate as new SQLiteParameter("#startDate")
startDate.Value = DateTimePicker2.Value
Dim endDate as new SQLiteParameter("#endDate")
endDate.Value = DateTimePicker3.Value
MyCmd.Parameters.Add(startDate)
MyCmd.Parameters.Add(endDate)
Dim Da As New SQLiteDataAdapter(MyCmd)
Dim Ds As New DataSet
Dim Dt As New DataTable
Ds.Reset()
Da.Fill(Ds)
Dt = Ds.Tables(0)
Dim Bs As New BindingSource With {.DataSource = Dt}
DataGridView1.DataSource = Bs
Bs.MoveLast()
MyConn.Close()
MyCmd.Dispose()
MyConn.Dispose()
End Using
End Using
This should help you resolve your issue.
Try
conn = New SqlConnection(strcon)
conn.Open()
Dim str As String = "select * from MYTABLE where Year >='#" & Txtfromyear_reprt.Text & "#' and Year <='#" & Txttoyear_reprt.Text & "#'"
da = New SqlDataAdapter(str, conn)
Dim ds As New DataSet
da.Fill(ds, "MYTABLE")
DgvReport.DataSource = ds.Tables("MYTABLE")
da.Dispose()
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
I'm working with my school project but I've encountered a problem in which I can't solve. I wrote this code in my search button but when I click it at runtime, no data is displayed in my datagrid.
What I want is when I click it I want to display all the data from mytable to the Datagrid view using two textboxes. I have two textboxes, txtfromyear and txttoyear and a database column Year with a datatype nvarchar(50).
Please help me, thank you in advance.
Don't use string concatenation to build your sql queries, NEVER!
You are open for sql injection, there is no excuse for it. Instead use sql parameters:
Dim dateFrom as Date
Dim dateTo as Date
Dim validFromDate = Date.TryParse(Txtfromyear_reprt.Text.Trim(), dateFrom)
Dim validToDate = Date.TryParse(Txttoyear_reprt.Text.Trim(), dateTo)
Now exit this method with a meaningful message if the user didn't provide valid dates. You can check validFromDate and validToDate which are booleans. The rest of the code is executed If validFromDate AndAlso validToDate:
Dim str As String = "select * from MYTABLE where Year >= #fromyear and Year <= #toyear"
da = New SqlDataAdapter(str, conn)
da.SelectCommand.Parameters.Add("#fromyear", SqlDbType.DateTime).Value = dateFrom
da.SelectCommand.Parameters.Add("#toyear", SqlDbType.DateTime).Value = dateTo
' now you can use da.Fill(ds, "MYTABLE") safely
I just saw you use varchar to store datetimes. Why? Fix it in the database.
Dim sql As String = "SELECT * FROM old where inputdate BETWEEN '" + DateTimePicker2.Value.ToShortDateString() + "' AND '" + DateTimePicker3.Value.ToShortDateString() + "';"
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "old_table")
connection.Close()
I have 2 DateTimePickers of format Short. In SQL, the column name "inputdate" of DataType: date.
When I choose dates with days <= 12, everything is working fine. When I choose dates with days > 12, I am having this error. I can see it's a matter of day and month but i'm still can't get the solution.
Any help is really appreciated": Conversion failed when converting date and/or time from character string.
I advice you to use the Parameter to use SqlDbType.DateTime and then pass the DateTime directly to the parameter (do not need to convert) , and also avoid SQL injections , like this :
Dim sql As String = "SELECT * FROM old where inputdate BETWEEN #startDate AND #endDate;"
Dim cmd As New SqlCommand(sql, connection)
cmd.Parameters.Add("#startDate", SqlDbType.DateTime).Value = DateTimePicker2.Value
cmd.Parameters.Add("#endDate", SqlDbType.DateTime).Value = DateTimePicker3.Value
Dim dataadapter As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "old_table")
connection.Close()
the output format of ToShortDateString() is not valid for sql server, and sql mixes the days with months.
try this
Dim sql As String = "SELECT * FROM old where inputdate BETWEEN '" + DateTimePicker2.Value.ToString("yyyy-MM-dd") + "' AND '" + DateTimePicker3.Value.ToString("yyyy-MM-dd") + "';"
read this more more information.
Try this:
Dim dt1 as sring = String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(DateTimePicker2.Value.ToShortDateString()))
Dim dt2 as sring = String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(DateTimePicker3.Value.ToShortDateString()))
Dim sql As String = "SELECT * FROM old where inputdate BETWEEN '" + dt1 + "' AND '" + dt2 + "';"
Dim dataadapter As New SqlDataAdapter(sql, connection)
The basic solution is that you have to provide date into either mm/DD/YYYY format or in YYYY-MM-DD date format into ms-sql query.
So, before passing date to query convert your date into either mm/DD/YYYY format or in YYYY-MM-DD format.
i need to select some records from table Tr_cashbook between two date. the date field is newdt in which i need to compare data and the records should be shown in crystal report named rptCash2. the newdt field has datetime property. here is the code on the command button
bdcon.Open()
Dim QueryString As String
QueryString = "Select * from Tr_Cashbook where (Cast(newdt as date)>= " & DateTimePicker1.Value.ToString("yyyy-MM-dd") & ") and (Cast(newdt as date) <= " & DateTimePicker2.Value.ToString("yyyy-MM-dd") & ")"
Dim Adapter As SqlDataAdapter = New SqlDataAdapter(QueryString, bdcon)
Dim ds As DataSet = New DataSet()
Adapter.Fill(ds, "Tr_Cashbook")
rptCash2.Load()
rptCash2.SetDataSource(ds)
CrystalReportViewer1.ReportSource = rptCash2
bdcon.Close()
but this is not working
when i press the command button it gives error as operand type clash: date is incompatible with int. i am not able to find out where i go wrong . help me with this..
Use parameters instead of hard-coded sql string.
Your parameterized query shoud be:
QueryString = "Select * from Tr_Cashbook where newdt>=#date1 and
newdt<= #date2"
Dim Cmd as new SqlCommand(QueryString,bdcon)
Cmd.Parameters.Add("#date1",SqlDbType.Date).Value=DateTimePicker1.Value
Cmd.Parameters.Add("#date2",SqlDbType.Date).Value=DateTimePicker2.Value
Dim Adapter As SqlDataAdapter = New SqlDataAdapter(Cmd)
Dim ds As DataSet = New DataSet()
Adapter.Fill(ds, "Tr_Cashbook")
You may use BETWEEN AND syntax:
QueryString = "Select * from Tr_Cashbook where newdate BETWEEN #date1 AND #date2"
Dim Con As OleDb.OleDbConnection
Dim Sql As String = Nothing
Dim Reader As OleDb.OleDbDataReader
Dim ComboRow As Integer = -1
Dim Columns As Integer = 0
Dim Category As String = Nothing
Dim oDatumMin As Date
Dim column As String
column = Replace(TxtDateMax.Text, "'", "''")
'oDatumMin = Convert.ToDateTime(TxtDateMin.Text)
oDatumMin = DtpMin.Value
Dim oPath As String
oPath = Application.StartupPath
' Select records.
Con = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & oPath & "\trb.accdb;")
Dim cmd As New OleDb.OleDbCommand
'Dim data_reader As OleDbDataReader = cmd.ExecuteReader()
Sql = ("SELECT * FROM " & cmbvalue & " WHERE Datum>='" & oDatumMin & "'")
cmd = New OleDb.OleDbCommand(Sql, Con)
Con.Open()
Reader = cmd.ExecuteReader()
Do While Reader.Read()
Dim new_item As New ListViewItem(Reader.Item("Datum").ToString)
new_item.SubItems.Add(Reader.Item("Steleks i krpe za cišcenje-toal papir-ubrusi-domestos").ToString)
new_item.SubItems.Add(Reader.Item("TEKUCINA ZA CIŠCENJE PLOCICA").ToString)
new_item.SubItems.Add(Reader.Item("KESE ZA SMECE").ToString)
new_item.SubItems.Add(Reader.Item("OSTALO-džoger-spužva za laminat").ToString)
new_item.SubItems.Add(Reader.Item("PAPIR").ToString)
LvIzvjestaj.Items.Add(new_item)
Loop
' Close the connection.strong text
Con.Close()``
when i select table,(cmbvalue) from combobox
and when i select date from datetime picker (dtp) or in last case from texbox converted to date and time sql looks like this "SELECT * FROM Uprava WHERE Datum>='2.6.2010 10:28:14'"
and all query looks ok but am geting
Data type mismatch in criteria expression. error for date (oDatumMin) when excute
column in access is also set to date
i have no idea what else to try
I suspect this is a localisation issue. Try changing the date format to one which should be universally recognised:
SELECT * FROM Uprava WHERE Datum >='2010/06/02 10:28:14'
[What is your server locale/code page?]
Dim sql As String = "SELECT * FROM MyTable WHERE Datum >= ?"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(sql)
cmd.Parameters.Add(New OleDb.OleDbParameter("#Datum", OleDb.OleDbType.Date))
cmd.Parameters("Datum").Value = oDatumMin
http://msdn.microsoft.com/de-de/library/bbw6zyha.aspx