gpt4 book ai didi

oracle - Godror SQL驱动程序和一部分结构

转载 作者:行者123 更新时间:2023-12-03 10:09:06 25 4
gpt4 key购买 nike

我正在使用Go打开带有多个JSON条目的文件,将文件解析为具有自定义类型的 slice ,然后将 slice 数据插入Oracle数据库。根据https://godror.github.io/godror/doc/tuning.html上的godror文档,我应该能够将一个 slice 送入insert命令,并让database/sql Exec方法为我遍历该结构。我不知道该怎么做。我敢肯定有一个简单的解决方案。
为了使事情稍微复杂一点,我有一个数据库列,该列不在用于运行应用程序的计算机的主机名的结构中。应用插入的每一行都应填写此列。换句话说,该表的每一行都需要填充一列,其中包含正在运行的计算机的主机名。除了将“hostname”字段一遍又一遍地添加到具有运行系统主机名的结构中,还有一种更优雅的方法吗?
接下来是我的代码的简化版本。

package main

import (
"database/sql"

_ "github.com/godror/godror"
)

type MyType struct {
var1 string `json:"var1"`
var2 string `json:"var2"`
}

func main() {
hostname, err := os.Hostname()

if err != nil {
//log.Println("Error when getting host name")
log.Fatal(err)
}

mySlice := parseFile("/path/to/file", false)

db, err := sql.Open("godror", "user/pass@oraHost/oraDb")
sql := `INSERT INTO mytable (var1, var2, host) values (:1 :2 :3)`

// this is the line where everything breaks down, and i am not sure
// what should go here.
_, err = db.Exec(sql, mySlice[var1], mySlice[var2], hostname)
}

func parseFile(filePath string, deleteFile bool) []MyType {
// a few lines of code that opens a text file, parses it into a slice
// of type MyType, and returns it
}

最佳答案

不确定(如果您已经通过)此测试用例TestExecuteMany是否有帮助? https://github.com/godror/godror/blob/master/z_test.go中提到的示例具有数组插入的示例用法。

res, err := tx.ExecContext(ctx,
`INSERT INTO `+tbl+ //nolint:gas
` (f_id, f_int, f_num, f_num_6, F_num_5_2, F_vc, F_dt)
VALUES
(:1, :2, :3, :4, :5, :6, :7)`,
ids, ints, nums, int32s, floats, strs, dates)

对于批量插入结构:
https://github.com/jmoiron/sqlx

关于oracle - Godror SQL驱动程序和一部分结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66162251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com