如何计算VB.NET的到期日期

时间:2017-02-20 21:16:17

标签: sql vb.net

 Dim readers As MySqlDataReader

    cn.Open()
    Dim query As String
    query = "Select * from tblmeds where expdate='" & DateTime.Now & "'"
    command = New MySqlCommand(query, cn)
    readers = command.ExecuteReader

    Dim count As Integer
    count = 0
    While readers.Read
       count = count + 1
    End While

        cn.Close()

        If count = 0 Then

           MsgBox("no expiration")
        Else
            MsgBox("medicine at risk")
        End If

这只是我制作的代码,但它不起作用,因为它不会去,而是如果count = 0则直接进行。另外我怎么能对我的节目说“如果数据库上的截止日期是接近一个月我设置为”抱歉我的英语不好

2 个答案:

答案 0 :(得分:2)

您正在检查您的任何商品的有效期是否完全等于DateTime.Now的当前值。此属性还包含时间部分,因此您的项目具有完全相同的值是非常不可能的。

我认为你会使用' expdate比现在更少'因此你的代码应该是

Dim readers As MySqlDataReader
cn.Open()
Dim query As String
query = "Select * from tblmeds where expdate<=@exp"
command = New MySqlCommand(query, cn)
command.Parameters.Add("@exp", MySqlDbType.DateTime).Value = DateTime.Now;
readers = command.ExecuteReader
Dim count As Integer
count = 0
While readers.Read
   count = count + 1
End While
cn.Close()
If count = 0 Then
    MsgBox("no expiration")
Else
    MsgBox("medicine at risk")
End If

相反,如果您要检查到期日期是否等于今天的日期,那么要使用的表达式是DateTime.Today而不是DateTime.Now。

另请注意,从不连接字符串以形成sql查询是一种非常好的做法。始终使用参数方法来避免解析和转换错误。

答案 1 :(得分:0)

为什么不使用时间戳差异:

query = "Select * from tblmeds where TIMESTAMPDIFF(MONTH,`expdate`,CURRENT_TIMESTAMP())< 1"
相关问题