Visual Basic 2010将当前日期插入数据库

时间:2015-09-19 11:45:12

标签: visual-studio-2010 datetime

我似乎无法将当前时间添加到我的数据库中。我尝试过以下方法:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
        dataFile = "F:\daniel\Sample Program\database\attendance.accdb"
        connString = provider & dataFile
        myConnection.ConnectionString = connString
        myConnection.Open()

    Dim Timein As Date
    Timein = Now()
    Timein = "insert into timesheet (time1) values (NOW())"
    Dim cmd As OleDbCommand = New OleDbCommand(Timein, myConnection)
    cmd.Parameters.Add(New OleDbParameter("time1", CType(Button1.Text, Date)))

    Try
        cmd.ExecuteNonQuery()
        cmd.Dispose()
        myConnection.Close()
    Catch ex As Exception
        MsgBox(ex.Message)
        myConnection.Close()



    End Try

End Sub

2 个答案:

答案 0 :(得分:0)

试试这个:

Dim Timein As Date
Timein = Now()
Dim sqlText as String
sqlText = "insert into timesheet (time1) values (timeParam)"
Dim cmd As OleDbCommand = New OleDbCommand(sqlText, myConnection)
cmd.Parameters.Add(New OleDbParameter("timeParam", Timein))

免责声明:这是从记忆中完成的,未经过测试。

编辑添加:如何一次插入两个值:

 Dim sqlText as String
 sqlText = "insert into timesheet (time1, time2) values(timeParam1, timeParam2)"
 Dim cmd as OleDbCommand = New OleDbCommand(sqlText, myConnection)
 cmd.Parameters.Add(New OleDbParameter("timeParam1", Timein))
 cmd.Parameters.Add(New OleDbParameter("timeParam2", Timeout))

如果您需要做的是稍后再回来并使用第二个值更新您的第一个时间表行,则需要Update语句。发布另一个问题。

要修改时间表值的显示方式,可以使用String.Format()功能:

  txtTime1.Text = String.Format("{0:yyyy-MM-dd hh:mm:ss}", Timein)

用作第一个参数的长字符串是custom format string:你可以在Custom Date and Time Format Strings阅读它们。

答案 1 :(得分:0)

  • 如果您要当前日期和时间(例如:27/12/2019 12:00)

sql =“ INSERT INTO TableName(id,date)VALUES(” 1“,'” NOW“',”);“

  • 如果您只想当前日期(例如:27/12/2019)

sql =“ INSERT INTO TableName(id,date)VALUES(” 1“,'” TODAY“',”);“