我有一段代码可以归结
为dim stmt as dao.queryDef
dim parId as dao.parameter
set stmt = currentDB().createQueryDef("", _
"parameters id guid, ...; insert into tab (id, ... ) values ([id], ...)")
我创建了表格
create table tab (
id guid,
...
)
和
alter table tab add constraint tab_pk primary key (id)
稍后,我想将 GUID 分配给parId
:
parId.value = GuidFromString("{936DA01F-9ABD-4D9D-80C7-02AF85C822A8}")
此分配会导致运行时错误 3421:Data type conversion error
。
如何将 GUID 分配给dao.parameter
变量?
更新的示例
这是一个更新的示例,它使用在我的环境中不起作用的longbinary
参数:执行stmt.execute
时会导致运行时错误 3001(无效参数)。
option explicit
sub main() ' {
dim db as dao.database
set db = application.currentDB
' db.execute("drop table tab")
createTable db
insertValues db
end sub ' }
sub createTable(db as dao.database) ' {
db.execute( _
"create table tab ( " & _
" id guid, " & _
" txt char(60) " & _
")")
db.execute("alter table tab add constraint tab_pk primary key (id)")
end sub ' }
sub insertValues(db as dao.database) ' {
dim stmt as dao.queryDef
set stmt = db.createQueryDef("", _
"parameters " & _
" id longbinary, " & _
" txt char(60); " & _
"insert into tab values ([id], [txt]) ")
dim parId as dao.parameter
dim parTxt as dao.parameter
set parId = stmt.parameters("id" )
set parTxt = stmt.parameters("txt")
parId.value = GuidFromString("{936DA01F-9ABD-4D9D-80C7-02AF85C822A8}")
parTxt.value = "Hello world."
stmt.execute ' Access throws Runtime Error 3001 (Invalid argument)
end sub ' }
GUID 类型是一种特殊类型,不能作为参数使用。
相反,请使用 LONGBINARY
将 GUID 作为二进制数据传递给查询:
set stmt = currentDB().createQueryDef("", _
"parameters id LONGBINARY, ...; insert into tab (id, ... ) values ([id], ...)")
针对新的MCVE:
主要错误是VARCHAR
声明。以下修改有效:
Sub insertValues(db As dao.Database) ' {
Dim stmt As dao.QueryDef
Set stmt = db.CreateQueryDef("", _
"parameters " & _
" idparam LONGBINARY ;" & _
"insert into tab(ID) values ([idparam]) ")
Dim parId As dao.Parameter
Dim parTxt As dao.Parameter
Set parId = stmt.Parameters("idparam")
'Set parTxt = stmt.Parameters("txtparam")
stmt.Parameters!idparam.Value = GUIDFromString("{936DA01F-9ABD-4D9D-80C7-02AF85C822A8}")
'stmt.Parameters!txtparam.Value = "Hello world."
stmt.Execute 'no errors
End Sub ' }
和
Sub insertValues(db As dao.Database) ' {
Dim stmt As dao.QueryDef
Set stmt = db.CreateQueryDef("", _
"parameters " & _
" idparam BINARY, txtparam CHAR(60) ;" & _
"insert into tab values ([idparam], txtparam) ")
Dim parId As dao.Parameter
Dim parTxt As dao.Parameter
Set parId = stmt.Parameters("idparam")
Set parTxt = stmt.Parameters("txtparam")
stmt.Parameters!idparam.Value = GUIDFromString("{936DA01F-9ABD-4D9D-80C7-02AF85C822A8}")
stmt.Parameters!txtparam.Value = "Hello world."
stmt.Execute 'no errors
End Sub ' }