Golang中如何将NULL值传递给SQLPOINTER

Golang中如何将NULL值传递给SQLPOINTER

func SQLColAttribute(statementHandle SQLHSTMT, ColumnNumber SQLSMALLINT, FieldIdentifier SQLSMALLINT, CharacterAttributePtr SQLPOINTER, BufferLength SQLSMALLINT, StringLengthPtr *SQLSMALLINT, NumericAttributePtr SQLPOINTER) (ret SQLRETURN) {

r0, _, _ := syscall.Syscall9(procSQLColAttribute.Addr(), 7, uintptr(statementHandle), uintptr(ColumnNumber), uintptr(FieldIdentifier), uintptr(CharacterAttributePtr), uintptr(BufferLength), uintptr(unsafe.Pointer(StringLengthPtr)), uintptr(NumericAttributePtr), 0, 0)

ret = SQLRETURN(r0)

return

}

上述函数中的 FieldIdentifier 会改变,如果返回值是整数类型,那么 NumericAttributePtr 将保存结果,而其他参数 StringLengthPtr 和 CharacterAttributePtr 必须为空。

ret := api.SQLColAttribute(r.os.h, api.SQLSMALLINT(i), api.SQL_DESC_PRECISION, nil, 0, nil, &Col[index])

由于 Go 语言有 NIL,如果我使用 NIL,会产生无法将 NIL 存储到 SQLPOINTER 的错误;如果我使用 NULL,会显示 NULL 未定义。

如何解决这个问题?谢谢。


更多关于Golang中如何将NULL值传递给SQLPOINTER的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang中如何将NULL值传递给SQLPOINTER的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go语言中,要将NULL值传递给SQLPOINTER参数,需要使用unsafe.Pointer(nil)而不是简单的nilNULL

SQLPOINTER在ODBC API中通常定义为unsafe.Pointer类型,当需要传递NULL指针时,应该使用类型转换后的nil值。

以下是正确的调用方式:

// 当需要传递NULL SQLPOINTER时
ret := api.SQLColAttribute(
    r.os.h, 
    api.SQLSMALLINT(i), 
    api.SQL_DESC_PRECISION, 
    unsafe.Pointer(nil),  // CharacterAttributePtr 为 NULL
    0, 
    nil,                  // StringLengthPtr 为 nil (已经是*SQLSMALLINT类型)
    &Col[index]           // NumericAttributePtr 指向有效地址
)

或者更完整的示例:

import "unsafe"

// 当所有指针参数都需要为NULL时
ret := api.SQLColAttribute(
    statementHandle,
    columnNumber,
    fieldIdentifier,
    unsafe.Pointer(nil),  // CharacterAttributePtr 为 NULL
    0,
    nil,                  // StringLengthPtr 为 nil
    unsafe.Pointer(nil),  // NumericAttributePtr 为 NULL
)

关键点:

  • 对于SQLPOINTER类型的参数,使用unsafe.Pointer(nil)
  • 对于普通的Go指针类型(如*SQLSMALLINT),直接使用nil即可
  • 这种区别是因为SQLPOINTER在Go绑定中通常被定义为unsafe.Pointer类型,需要进行显式的类型转换

在你的具体用例中,当FieldIdentifier表明返回整数类型时,正确的调用应该是:

ret := api.SQLColAttribute(
    r.os.h,
    api.SQLSMALLINT(i),
    api.SQL_DESC_PRECISION,
    unsafe.Pointer(nil),  // NULL SQLPOINTER
    0,
    nil,                  // nil *SQLSMALLINT  
    &Col[index]           // 有效的NumericAttributePtr
)
回到顶部