33

我在 Go 应用程序中使用jmoiron/sqlx库与我的 PostgreSql 服务器进行通信。在我的应用程序的某个地方,我有以下代码:

sqlQuery := `
    INSERT INTO table_to_insert  (
        code,
        status,
        create_time,
        create_by
    ) VALUES (
        '',
        0,
        CURRENT_TIMESTAMP,
        0
    ) RETURNING id
`

datas, err := tx.NamedExec(sqlQuery, structToInsert)

问题:如何使用 return from 获取最后一个插入 id tx.NamedExec()?我试过datas.LastInsertId()了,但它总是返回 0。

注意:我确定插入到 postgres 是成功的。

4

2 回答 2

50

The reason for this is because PostgreSQL does not return you the last inserted id. This is because last inserted id is available only if you create a new row in a table that uses a sequence.

If you actually insert a row in the table where a sequence is assigned, you have to use RETURNING clause. Something like this: INSERT INTO table (name) VALUES("val") RETURNING id".

I am not sure about your driver, but in pq you will do this in the following way:

lastInsertId := 0
err = db.QueryRow("INSERT INTO brands (name) VALUES($1) RETURNING id", name).Scan(&lastInsertId)
于 2016-06-12T08:03:02.777 回答
6

resp.LastInsertID()仅(通常)适用于 mySQL,并且仅适用于整数 ID:https ://golang.org/pkg/database/sql/#Result

请注意,由于您正在使用sqlx(通过使用NamedExec),您将希望改为使用tx.Get来执行查询并捕获返回值:

// id should match the type of your ID 
// e.g. int64 for a bigserial column, or string for a uuid
var id string
resp, err := tx.Get(&id, query, v1, v2, v3)

请参阅 sqlx GitHub 存储库上的相关讨论:https ://github.com/jmoiron/sqlx/issues/154#issuecomment-148216948

于 2015-10-28T05:15:17.017 回答