sheik
sheik

Reputation: 513

Record inserted twice into database

I have code in Go like below :

package main

import (  
  "database/sql"
  "log"

  _ "github.com/lib/pq"

)


const (
    insertLoginSQL   = `insert into Logins(id, name,password) values($1, $2, $3)`
)

func main() {  

     db, err := sql.Open("postgres", "user=postgres password=admin dbname=Quality sslmode=disable")

    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    if err := Insert(db); err != nil {
        log.Println("error with double insert", err)
    }

}

func Insert(db *sql.DB) error {
    tx, err := db.Begin()
    if err != nil {
        return err
    }

        stmt, err := tx.Prepare(insertLoginSQL)
        if err != nil {
            return err
        }
        defer stmt.Close()

        if _, err := stmt.Exec(10, "user","pwd"); err != nil {
            tx.Rollback()
            return err
        }

    return tx.Commit()
}

When I run above code, records inserted twice in database. Can someone let me know why duplicate records inserted? Any issue with this code?

Upvotes: 0

Views: 1002

Answers (1)

Vyacheslav
Vyacheslav

Reputation: 156

Probably commit is done twice. First time by some of previous operations like stmt.exec and second time when tx.Commit() executed.

Upvotes: 2

Related Questions