每次显示或加载表单时用当前日期填充一列
Posted
技术标签:
【中文标题】每次显示或加载表单时用当前日期填充一列【英文标题】:Filling a column with the current date each time the form is shown or loaded 【发布时间】:2020-02-20 15:07:20 【问题描述】:我想用当前日期填充列中的所有条目,以便我可以将它与 DateofTest 列进行比较,并确定自上次测试以来的天数。我想我可以算出天数,但我不知道如何用当前日期填充列。
Private Sub Reports_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
mysql = "Update Studentdata, SET currentDate = Date()"
ConnDB()
myCommand = New OleDbCommand(mySql, myConnection)
End Sub
【问题讨论】:
我觉得你不需要逗号,试试“Update Studentdata SET currentDate = Date()” 不走运。这很奇怪,因为我没有收到错误。它只是对列没有任何作用。 【参考方案1】:你真的在执行更新命令吗?试试这个:
Dim myConnection As New OleDb.OleDbConnection() 'Complete as needed
Dim mySql As String = "Update Studentdata SET currentDate = Date()"
Using cmd As New OleDb.OleDbCommand(mySql, myConnection)
Try
cmd.Connection.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message, "ERROR UPDATING")
Finally
cmd.Connection.Close()
End Try
End Using
或尝试从您的代码中填充日期并将其作为参数提供,如下所示:
Using cmd As New OleDb.OleDbCommand()
cmd.Connection = myConnection
Try
cmd.Connection.Open()
cmd.CommandText = "Update Studentdata SET currentDate = @Date"
cmd.Parameters.Add(New OleDb.OleDbParameter("@Date", DateTime.Now))
cmd.ExecuteNonQuery()
Catch ex1 As Exception
MessageBox.Show(ex1.Message, "ERROR UPDATING")
Finally
cmd.Connection.Close()
End Try
End Using
【讨论】:
成功了。我添加了 mycommand.ExecuteNonQuery() 并且效果很好。【参考方案2】:据我所知,访问数据库在包含毫秒的日期方面可能存在一些问题,因此您可以这样做(也可以删除“SET”之前的逗号):
Dim dateWithoutMiliseconds as DateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day)
mySql = String.Format("Update Studentdata SET currentDate = 0", dateWithoutMiliseconds)
【讨论】:
以上是关于每次显示或加载表单时用当前日期填充一列的主要内容,如果未能解决你的问题,请参考以下文章