标签: sqlx

使用 sqlx 选择并获取用法

我正在使用 go 1.10.3,并且尝试使用 sqlx 包获取一行并将其输入到带有 的结构中Get(),或者获取几行并将它们输入到带有 的切片中Select()

让我们从将一行放入结构体开始。

我创建了以下结构:

type PsqlProduct struct {
    Id              int64          `db:"product_id"`
    Name            string         `db:"product_name"`
    Desc            sql.NullString `db:"product_desc"`
    YearManufacture sql.NullInt64  `db:"year_manufacture"`
    Quantity        sql.NullInt64  `db:"quantity"`
}
Run Code Online (Sandbox Code Playgroud)

对于查询:

QUERY_SELECT_PRODUCT = `select wd.product.id as product_id,
trans_p_name.text as product_name,
trans_p_desc.text as product_desc,
wd.product.year_manufacture, wd.product.quantity
from wd.product
join wd.text_translation as trans_p_name 
    on trans_p_name.text_id = wd.product.product_name_trans_id and trans_p_name.lang_id=1
left join wd.text_translation as trans_p_desc 
    on trans_p_desc.text_id = wd.product.product_desc_trans_id and trans_p_desc.lang_id=1
where wd.product.id = $1 
`
Run Code Online (Sandbox Code Playgroud)

我创建了以下函数来通过 id 获取产品:

func …
Run Code Online (Sandbox Code Playgroud)

go sqlx

3
推荐指数
1
解决办法
1万
查看次数

sqlx.Connect()和sqlx.Open()有什么区别?

我正在为我的golang项目使用jmoiron sqlx库.我试图创建一个db连接mysql.所以,我发现了这两个功能:sqlx.Connect()并且sqlx.Open(),但没有发现差异.

所以,我试着用godoc阅读文档.我找到了这个:

sqlx.Connect()

Connect to a database and verify with a ping.
Run Code Online (Sandbox Code Playgroud)

sqlx.Open()

Open is the same as sql.Open, but returns an *sqlx.DB instead.
Run Code Online (Sandbox Code Playgroud)

我知道sqlx.Open()使用golang创建与数据库的连接sql.Open.但有什么sqlx.Connect()用?

如果我在这里看到源代码:

func Connect(driverName, dataSourceName string) (*DB, error) {
    db, err := Open(driverName, dataSourceName)
    if err != nil {
        return nil, err
    }
    err = db.Ping()
    if err != nil {
        db.Close()
        return nil, err
    }
    return db, nil
}
Run Code Online (Sandbox Code Playgroud)

我可以看到它调用相同 …

go sqlx

3
推荐指数
1
解决办法
846
查看次数

如何从sqlx获取最后插入行的id?

我想使用以下方法取回插入 MySql 数据库的最后一篇文章的 id sqlx

resultPost, err := shared.Dbmap.Exec("INSERT INTO post (user_id, description, link) VALUES (?, ?, ?)", userID, title, destPath)
if err != nil {
    log.Println(err)
    c.JSON(
        http.StatusInternalServerError,
        gin.H{"error": "internal server error"})
}

fmt.Println("resultPost is:", resultPost)
Run Code Online (Sandbox Code Playgroud)

问题是 被resultPost打印为对象:

resultPost is: {0xc420242000 0xc4202403a0}
Run Code Online (Sandbox Code Playgroud)

所以我想知道提取刚刚插入的行的 id 的正确方法是什么?

mysql sql go sql-insert sqlx

3
推荐指数
1
解决办法
5675
查看次数

如何将sqlx查询结果转换为结构体数组?

我试图在没有 where 条件的情况下查询 postgres 表中的所有结果,并通过传递 args ...interface {} 借助 sqlx db 查询将其映射到结构数组。

但是下面粘贴的代码永远不会工作,而不是一一迭代和扫描结果,是否可以让以下代码工作?

非常感谢您的投入。谢谢

type CustomData struct {
    ID                        string `db:"id" json:",omitempty"`
    Name                      string `db:"name" json:",omitempty"`
    Description               string `db:"description" json:",omitempty"`
    SourceID                  string `db:"sourceid" json:",omitempty"`
    StatusID                  string `db:"statusid" json:",omitempty"`
    StatusReason              string `db:"statusreason" json:",omitempty"`
    CreateTime                string `db:"createtime" json:",omitempty"`
    UpdateTime                string `db:"updatetime" json:",omitempty"`
}

var myData []CustomData

*sqlx.DB.Query("SELECT id as ID,  name as Name, description as Description, sourceid as SourceID, statusid as StatusID, statusreason as StatusReason, createtime as CreateTime, updatetime as UpdateTime FROM …
Run Code Online (Sandbox Code Playgroud)

go sqlx

3
推荐指数
1
解决办法
8353
查看次数

如何在golang中将变量id传递给statement.Query()?

我在 postgres 中有这个查询,它根据传递的参数查询 1 或 n 个用户:

select name, phone from clients where id in ('id1','id2')
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试在 golang 中使用它时,我在如何将这种类型的变量参数传递给 statements.Query() 函数时遇到了问题:

ids := []string{"0aa6c0c5-e44e-4187-b128-6ae4b2258df0", "606b0182-269f-469a-bb29-26da4fa0302b"}
rows, err := stmt.Query(ids...)
Run Code Online (Sandbox Code Playgroud)

这会引发错误:Cannot use 'ids' (type []string) as type []interface{}

当我检查源代码查询时,它可以接收许多接口类型的变量:

func (s *Stmt) Query(args ...interface{}) (*Rows, error) {
    return s.QueryContext(context.Background(), args...)
}
Run Code Online (Sandbox Code Playgroud)

如果我手动执行此操作,它会起作用:

rows, err := stmt.Query("0aa6c0c5-e44e-4187-b128-6ae4b2258df0", "606b0182-269f-469a-bb29-26da4fa0302b")
Run Code Online (Sandbox Code Playgroud)

但当然我需要参数为 1 或更多,并且是动态生成的。

我正在使用 Sqlx 库。

go sqlx

2
推荐指数
1
解决办法
2168
查看次数

Golang 结构的 Postgres 数组

我有以下 Go 结构:

type Bar struct {
    Stuff string `db:"stuff"`
    Other string `db:"other"`
}

type Foo struct {
    ID    int    `db:"id"`
    Bars  []*Bar `db:"bars"`
}
Run Code Online (Sandbox Code Playgroud)

所以Foo包含一个Bar指针切片。我在 Postgres 中还有以下表格:

CREATE TABLE foo (
    id  INT
)

CREATE TABLE bar (
    id      INT,
    stuff   VARCHAR,
    other   VARCHAR,
    trash   VARCHAR
)
Run Code Online (Sandbox Code Playgroud)

我想LEFT JOIN在 table 上bar并将其聚合为一个数组以存储在 struct 中Foo。我试过了:

SELECT f.*,
ARRAY_AGG(b.stuff, b.other) AS bars
FROM foo f
LEFT JOIN bar b
ON f.id = …
Run Code Online (Sandbox Code Playgroud)

postgresql go sqlx

1
推荐指数
1
解决办法
5473
查看次数

使用 sqlx 批量插入

我正在尝试使用 sqlx 和 golang 进行批量插入:

    for _, result := range results {
            queryInsert := `INSERT INTO "DataCom_travel" (com1,com2,path,time) VALUES ($1,$2,$3,$4)`
            db.MustExec(queryInsert,result.Com1,result.Com2,result.Path,result.Time)
            queryUpdate := `UPDATE "DataCom_commcombinaison" set done = TRUE WHERE com1 =$1 and com2 =$2`
            db.MustExec(queryUpdate,result.Com1,result.Com2)
        }
Run Code Online (Sandbox Code Playgroud)

该代码有效,但速度很慢。

我试过这个:

tx := db.MustBegin()
for _, result := range results {
        queryInsert := `INSERT INTO "DataCom_travel" (com1,com2,path,time) VALUES ($1,$2,$3,$4)`
        tx.MustExec(queryInsert,result.Com1,result.Com2,result.Path,result.Time)
        queryUpdate := `UPDATE "DataCom_commcombinaison" set done = TRUE WHERE com1 =$1 and com2 =$2`
        tx.MustExec(queryUpdate,result.Com1,result.Com2)
    }
tx.Commit()
Run Code Online (Sandbox Code Playgroud)

但是当我查看我的记录时它什么也没做,我没有看到任何记录。

问候

编辑 :

INSERT …
Run Code Online (Sandbox Code Playgroud)

postgresql go sqlx

0
推荐指数
3
解决办法
5635
查看次数

标签 统计

go ×7

sqlx ×7

postgresql ×2

mysql ×1

sql ×1

sql-insert ×1