Return value from INSERT INTO (sqlx)

I am trying to use AJAX to call a Go API that inserts data into Postgresql.

  1. This is the query that is executed in Postgresql. Which work as query
    DB Fiddle - SQL Database Playground

  2. This is the API that inserts the query to Postgresql (using sqlx):

func endpoint { //simplified
    data = new(query, val)
    json.NewEncoder(w).Encode(data)

func new(query string, val string) interface{} {
    data := db.MustExec(query, val)
    return data
}
  1. This is the AJAX code that sends the REST request for all headers:
    Edit fiddle - JSFiddle - Code Playground
    OR this correct code for the text header that responds {"Locker":{}}:
    Edit fiddle - JSFiddle - Code Playground
    The desired result should be {“tsk_id”: “33”} (newly inserted number)

My goal is to fetch the newly added tsk_id from the INSERT INTO
It seems that the headers from MustExec not is updated or converted correctly.
Any clue welcome!

I’m not familiar with sqlx, but in plain ol’ database/sql, you use db.Query or db.QueryRow to execute your insert and then the RETURNING tsk_id part of the query is retrieved as a scalar value in that row.

1 Like

Thanks for pointing me in the right direction. This seems to work.

func Create(w http.ResponseWriter, r *http.Request) { // simplified
	data = new(query, val)
	json.NewEncoder(w).Encode(data)
}

// add new record
func new(query string, val string) interface{} {
	var id int
	err := db.QueryRowx(query, val).Scan(&id)
	if err != nil {
		return nil
	}
	return (id)
}

Edit fiddle - JSFiddle - Code Playground
The desired result is now {“120”} (newly inserted number)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.