package main
import (
"fmt"
"syscall"
"unsafe"
)
type goBson struct {
data uint64
cur uint64
dataSize int32
finished int32
stack [32]int
stackPos int
err int
errstr uint64
ownmem int
}
func main() {
var (
sdbConnectionHandle uint64
sdbCollectionHandle uint64
sdbCursorHandle uint64
rc int32
)
//加载动态链接库
h := syscall.MustLoadDLL("sdbc.dll")
//加载函数库
sdbConnect := h.MustFindProc("sdbConnect")
sdbDisconnect := h.MustFindProc("sdbDisconnect")
sdbReleaseConnection := h.MustFindProc("sdbReleaseConnection")
sdbGetCollection := h.MustFindProc("sdbGetCollection")
sdbQuery := h.MustFindProc("sdbQuery")
sdbNext := h.MustFindProc("sdbNext")
bsonToJson := h.MustFindProc("bsonToJson")
bson_sprint_length := h.MustFindProc("bson_sprint_length")
//连接数据库
urc, _, err := sdbConnect.Call(uintptr(unsafe.Pointer(syscall.StringBytePtr("192.168.10.100"))),
uintptr(unsafe.Pointer(syscall.StringBytePtr("11810"))),
uintptr(unsafe.Pointer(syscall.StringBytePtr(""))),
uintptr(unsafe.Pointer(syscall.StringBytePtr(""))),
uintptr(unsafe.Pointer(&sdbConnectionHandle)))
rc = int32(urc)
if rc != 0 {
fmt.Println(rc, err.Error())
return
}
//获取collection
urc, _, err = sdbGetCollection.Call(uintptr(sdbConnectionHandle),
uintptr(unsafe.Pointer(syscall.StringBytePtr("myTest.test1"))),
uintptr(unsafe.Pointer(&sdbCollectionHandle)))
rc = int32(urc)
if rc != 0 {
fmt.Println(rc, err.Error())
return
}
//查询
var (
skipNum int32 = 0
numToReturn int32 = -1
)
urc, _, err = sdbQuery.Call(uintptr(sdbCollectionHandle),
uintptr(unsafe.Pointer(nil)),
uintptr(unsafe.Pointer(nil)),
uintptr(unsafe.Pointer(nil)),
uintptr(unsafe.Pointer(nil)),
uintptr(skipNum),
uintptr(numToReturn),
uintptr(unsafe.Pointer(&sdbCursorHandle)))
rc = int32(urc)
if rc != 0 {
fmt.Println(rc, err.Error())
return
}
var count int32 = 0
//遍历
for {
var myBson goBson
urc, _, err = sdbNext.Call(uintptr(sdbCursorHandle),
uintptr(unsafe.Pointer(&myBson)))
rc = int32(urc)
if rc == -29 {
//读取结束
break
}
if rc != 0 {
fmt.Println(rc, err.Error())
break
}
count = count + 1
//获取json长度
bsonSize, _, err := bson_sprint_length.Call(uintptr(unsafe.Pointer(&myBson.data)))
if bsonSize == 0 {
fmt.Println(err.Error())
break
}
var (
toCSV int = 0
skip int = 0
)
size := int(bsonSize)
json := make([]byte, bsonSize)
bsonToJson.Call(uintptr(unsafe.Pointer(&json[0])),
uintptr(size),
uintptr(unsafe.Pointer(&myBson.data)),
uintptr(toCSV),
uintptr(skip))
//fmt.Println("json长度: " + fmt.Sprintf("%d", bsonSize))
fmt.Println(string(json[:bsonSize]))
}
fmt.Println("总共: " + fmt.Sprintf("%d", count))
sdbDisconnect.Call(uintptr(uintptr(sdbConnectionHandle)))
sdbReleaseConnection.Call(uintptr(uintptr(sdbConnectionHandle)))
}