我正在尝试在 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 等。
任何帮助将不胜感激。