我正在尝试使用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的几种变体,现在(Year)给出了yyyy-mm-dd等。
非常感谢任何帮助。
答案 0 :(得分:5)
datetime和user都是保留字,必须用方括号括起来。否则,它将在该日期运行。
INSERT INTO tabUpload(IDUPL, [DateTime], [User], DataCalc)
VALUES(0003, #17 August 2012 14:23:27#, 'UK\Pej', 'Calc')"
答案 1 :(得分:2)
您正在使用Vb.Net Now
并从中获取文字值,然后将该文字插入您的日期/时间字段。但是,Access数据库引擎提供了自己的Now()
函数,因此您可以在INSERT
语句中使用该函数。
INSERT INTO tabUpload (IDUPL, [DateTime], [User], DataCalc)
VALUES(3, Now(), 'UK\Pej', 'Calc')
答案 2 :(得分:0)