我需要创建一个每日报告,我在数据库中的输入将在图表中显示。
数据库名称:restoDB
表名:tlreports
字段:
ReportID- int
金额-小数
日期-日期时间
我需要显示当前日期和时间以及每小时的销售额。
这是我的代码,但它显示了数据库中存储的所有日期的所有输入:
Public Sub LoadChart()
Dim con As New MY_CONNECTION
Dim Reader As MySqlDataReader
Dim commanddate = New MySqlCommand("select * from tlreports ", con.getConnection())
Dim datetime = Val(txtboxDateTime.Text)
commanddate.Parameters.Add("@datetime", MySqlDbType.VarChar).Value = datetime
con.openConnection()
Reader = commanddate.ExecuteReader
While Reader.Read
chrtDaily.Series("Daily Income").Points.AddXY(Reader.GetDateTime("Date"), Reader.GetDecimal("Amount"))
End While
con.closeConnection()
End Sub
将数据库对象保留在使用它们的方法所在的本地,因此,您可以控制何时关闭和处置它们。 Using...End Using
块即使有错误也可以为您解决。
仅下拉所需的数据。在这种情况下,您只需要日期和金额。选择查询中没有任何参数,因此请不要在命令中添加参数。您的老师对Val
的判断有误。这是旧的VB6方法。 .net有更好的可用方法。 Val返回一个Double。您说Date
字段是DateTime
字段,所以Double
不能很好地工作。如果有人在txtboxDateTime文本框中输入12/04/2019,则Val
将返回12
。这就是您所期望的吗?
有关此不存在的参数的更多信息。如果确实需要一个参数,我很高兴您使用.Add方法,但是您在问题的顶部说日期字段为datetime类型,但是在您的.Add方法中,您将其数据类型指定为.VarChar。 ???
使用DataReader的问题是,在为图表构建系列时,连接必须保持打开状态。只需填写一个数据表,然后用End Using
关闭并放置连接和命令。然后,您可以将DataTable弄乱到您的内心满意。
我完全不熟悉Chart控件,但我不太了解Date如何提供X坐标。
Public Sub LoadChart()
Dim dt As New DataTable
Using con As New MySqlConnection("Your connection string"),
commanddate As New MySqlCommand("select Date, Amount from tlreports ", con)
con.Open()
dt.Load(commanddate.ExecuteReader)
End Using
For Each row As DataRow In dt.Rows
Chart1.Series("Daily Income").Points.AddXY(row("Date"), row("Amount"))
Next
End Sub