2015-10-28 50 views
7

我使用jmoiron/sqlx庫在我的Go應用程序中與我的PostgreSql服務器進行通信。某處在我的應用我有這個下面的代碼:轉到:如何使用NamedExec()獲取Postgresql上的最後一個插入ID

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) 

問:我怎樣才能利用tx.NamedExec()返回最後插入的ID?我試過datas.LastInsertId()但它總是返回0.

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

回答

9

重新這是因爲PostgreSQL不會返回您最後插入的ID。這是因爲只有在使用序列的表中創建新行時,上次插入的ID纔可用。

如果您實際在指定序列的表格中插入一行,則必須使用RETURNING clause。像這樣的:INSERT INTO table (name) VALUES("val") RETURNING id"

我不知道你的驅動程序,但在pq你會做到這一點通過以下方式:

lastInsertId := 0 
err = db.QueryRow("INSERT INTO brands (name) VALUES($1) RETURNING id", name).Scan(&lastInsertId) 
4

resp.LastInsertID()只(典型值)與MySQL的作品,並且只適用於整數ID:https://golang.org/pkg/database/sql/#Result

注意,因爲你正在使用sqlx(通過使用NamedExec)你要改用tx.Get給exec查詢並獲取返回值:

// 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