3

我正在尝试在 Visual Basic 中使用 SQL 将日期和时间值插入在 Access2002/3 模式下运行的 Access 2007 中。使用我的代码,我设法将文本字符串和数值插入到表中。但是,对于 DateTime 字段,会出现语法错误。Access 中的字段设置为日期/时间字段类型。

下面是我的第一个函数,它为数据库访问函数生成查询:

Public Function NewUpload(ByVal UploadType As String) As Single

    Dim UploadNumber As Single
    Dim ColumnString As String
    Dim ValueString As String

    If DatabaseConnection("SELECT ID_UPL FROM tabUpload", "Read Recordset") = "Error" Then GoTo close
    Do Until rdrOLEDB.Read = False
        If Val(rdrOLEDB.Item(0).ToString()) > UploadNumber Then UploadNumber = Val(rdrOLEDB.Item(0).ToString())
    Loop
    rdrOLEDB.Close()
    cnnOLEDB.Close()

    UploadNumber = UploadNumber + 1

    'Update Uploads table:
    ColumnString = "ID_UPL,DateTime,IDUser,DataCalc"
    ValueString = Format(UploadNumber, "0000") & ",#" & Now.ToLongDateString & " " & Now.ToLongTimeString & "#,'" & My.User.Name & "','" & UploadType & "'"
    If DatabaseConnection("INSERT INTO tabUpload(" & ColumnString & ") VALUES(" & ValueString & ")", "Non-Query") = "Error" Then GoTo Close

    NewUpload = UploadNumber

关闭:cnnOLEDB.Close()

End Function

这是连接到数据库的第二个函数

Public Function DatabaseConnection(ByVal Query As String, ByVal Task As String) As String
    'On Error GoTo Err

    cnnOLEDB.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DataDirectoryName & DatabaseFileName
    cmdOLEDB.Connection = cnnOLEDB
    cmdOLEDB.CommandText = Query
    cnnOLEDB.Open()

    Select Case Task
        Case "Read Recordset"
            rdrOLEDB = cmdOLEDB.ExecuteReader()
            DatabaseConnection = "Read Recordset"
        Case "Read Scalar"
            DatabaseConnection = Str(cmdOLEDB.ExecuteScalar)
        Case "Non-Query"
            DatabaseConnection = Str(cmdOLEDB.ExecuteNonQuery())
            DatabaseConnection = "Non-Query"
    End Select

    Exit Function
Err:
    MsgBox("Database connection error.")
    DatabaseConnection = "Error"

End Function

当我运行此代码时,我得到查询: INSERT INTO tabUpload(IDUPL, DateTime, User, DataCalc) VALUES(0003, #17 August 2012 14:23:27#, 'UK\Pej', 'Calc')"

我还尝试了 DateTime 的几种变体,使用格式和 now(Year) 给出 yyyy-mm-dd 等。

任何帮助将不胜感激。

4

3 回答 3

5

datetime 和 user 都是保留字,必须用方括号括起来。否则,它将在该日期运行。

 INSERT INTO tabUpload(IDUPL, [DateTime], [User], DataCalc) 
 VALUES(0003, #17 August 2012 14:23:27#, 'UK\Pej', 'Calc')"
于 2012-08-17T14:32:52.910 回答
2

您正在使用 Vb.NetNow并从中创建一个文字值,然后将该文字插入到您的日期/时间字段中。但是,Access db 引擎提供了自己的Now()函数,因此您可以在INSERT语句中使用该函数。

INSERT INTO tabUpload (IDUPL, [DateTime], [User], DataCalc)
VALUES(3, Now(), 'UK\Pej', 'Calc')
于 2012-08-17T15:07:31.660 回答
0

尝试以 ODBC 规范格式插入日期:

Format (Date, "yyyy-mm-ddThh:nn:ss")

这是format 函数的文档。

于 2012-08-17T14:33:40.893 回答