Build HTTP and database integrations

Insert Rows with Go database/sql and Retrieve Generated IDs

Insert a row with Go database/sql using ExecContext, bind values separately, and handle LastInsertId errors.

By Niko Minadze4 min read

Editorial illustration for Insert Rows with Go database/sql and Retrieve Generated IDs

For an INSERT that does not return rows, call DB.ExecContext with the SQL statement and its values as separate arguments. Check the execution error before touching the result. If the caller needs a generated ID, call Result.LastInsertId next and handle that error independently. The two errors tell you different things: one concerns executing the statement; the other concerns obtaining an ID from its result.

The following example uses the album table from the Go database access tutorial. In that table, id is generated automatically, while the insert supplies title, artist, and price. The code assumes the caller already has a usable *sql.DB connected through a compatible driver.

package album

import (
    "context"
    "database/sql"
    "fmt"
)

func AddAlbum(ctx context.Context, db *sql.DB, title, artist, price string) (int64, error) {
    result, err := db.ExecContext(
        ctx,
        "INSERT INTO album (title, artist, price) VALUES (?, ?, ?)",
        title, artist, price,
    )
    if err != nil {
        return 0, fmt.Errorf("insert album: %w", err)
    }

    id, err := result.LastInsertId()
    if err != nil {
        return 0, fmt.Errorf("retrieve inserted album ID: %w", err)
    }

    return id, nil
}

Keep the statement separate from its values

The question marks mark three value positions. The three arguments after the SQL string supply those values in order. This is the MySQL-style placeholder form used in the Go tutorial; use the placeholder syntax expected by your configured driver when adapting the example. database/sql is a generic interface used with a database driver, not a source of one universal SQL placeholder syntax.

Do not build the statement by formatting title, artist, or price into the SQL text. Keeping parameter values separate lets database/sql send them separately from the statement, which is the tutorial's recommended way to avoid SQL injection through those values. The column names and the number of placeholders remain part of the fixed statement; the record fields are arguments, not pieces of SQL to concatenate.

The example takes price as a string so a caller can supply a value such as "19.99" without the function formatting it into the query. The database and driver must still accept the supplied values for the table's columns. Parameter binding addresses how values enter the statement; it does not make an invalid value valid for a column.

Execute with the caller's context

ExecContext is appropriate here because this INSERT does not return a row to scan. It returns a result and an error, rather than *sql.Row or *sql.Rows. The database/sql overview describes context-taking database operations as a way to propagate cancellation or apply a deadline. Passing the caller's context through this function allows that control to reach the insert operation. The package documentation also notes an important qualification: a driver without context-cancellation support may not return until its query completes.

Check err from ExecContext before calling a method on result. Wrapping it with fmt.Errorf gives the caller a useful operation label while preserving the underlying error. There is no generated ID to report from this function when execution returns an error.

Treat ID retrieval as a separate outcome

A successful ExecContext call gives the function a sql.Result; it does not itself give the caller an ID. The tutorial obtains the ID with LastInsertId and checks that call's error separately. Follow that pattern only where the configured database and driver support getting the generated ID this way. Do not assume that every insert result can provide one.

If LastInsertId returns an error, AddAlbum returns 0 and an error labeled retrieve inserted album ID. That is a failure of this function's promise to return an ID, not an ExecContext error. In particular, the ID-retrieval error should not be reported as though the insert statement failed during execution. A caller that requires the ID can treat either error as a failure of its overall create-and-return-ID operation, while keeping those two failure points distinguishable.

When both calls succeed, AddAlbum returns the generated int64 ID with a nil error. The caller can then use that ID for the next step that needs to identify the new album. If the caller does not need an ID, it can choose a simpler insert function that checks ExecContext without making ID retrieval part of its success condition.

Comments

No comments yet.

Leave a comment

Your comment appears after approval. Plain text only; links stay as text. Line breaks and indentation are kept.

Up to 5,000 characters. No account or email needed.

All articles

Type at least two characters.

Press <kbd>Esc</kbd> to closeOpen the search page