0
votes

I have problem with my code , where I'm using library GORM to create or insert data to my restful api, print error say like this : (mssql: Violation of PRIMARY KEY constraint 'PK_SMSBlast2'. Cannot insert duplicate key in object 'dbo.SMSBlast2'. The duplicate key value is (0).)

package main

import (
    "encoding/json"
    "fmt"
    "github.com/gorilla/mux"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mssql"
    "log"
    "net/http"
    "time"
)

type SMSBlast struct { SequenceID int gorm:"column:SequenceID" MobilePhone string gorm:"column:MobilePhone" Output string gorm:"column:Output" WillBeSentDate *time.Time gorm:"column:WillBeSentDate" SentDate *time.Time gorm:"column:SentDate" Status *string gorm:"column:Status" DtmUpd time.Time gorm:"column:DtmUpd" }

func (SMSBlast) TableName() string {
    return "SMSBlast2"
}


func insertSMSBlast(w http.ResponseWriter, r *http.Request){
    fmt.Println("New Insert Created")

    db, err := gorm.Open("mssql", "sqlserver://sa:@localhost:1433?database=CONFINS")
    if err != nil{
        panic("failed to connect database")
    }
    defer db.Close()

    vars := mux.Vars(r)
    sequenceid := vars["sequenceid"]
    mobilephone := vars["mobilephone"]
    output := vars["output"]
    dtmupd := vars["dtmupd"]


sequenceid1,_ := strconv.Atoi(sequenceid)
prindata := db.Create(&SMSBlast{SequenceID: sequenceid1,MobilePhone: mobilephone, Output:output, DtmUpd: time.Now()})
fmt.Println(prindata)


}

func handleRequests(){
    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.HandleFunc("/smsblaststest",allSMSBlasts).Methods("POST")
    myRouter.HandleFunc("/smsblaststestInsert/{MobilePhone}/{DtmUpd}", insertSMSBlast).Methods("POST")
    log.Fatal(http.ListenAndServe(":8080",myRouter))

}

func main(){
    fmt.Println("SMSBLASTS ORM")
    handleRequests()
}
1
Determine what the primary key is, my guess is SequenceID. The error message means you are trying to insert a SequenceID that already exists. One thought is that you don't specifically provide a value, and it defaults to 0. Meaning after the first insert, all others will failSparky
@Sparky I have edit now and I get error multiple-value strconv.Atoi() in single-value context, so what happen now?dera ta

1 Answers

0
votes

It appears that for your table, the SequenceID is the primary key.

Your insert statement

 db.Create(&SMSBlast{MobilePhone: mobilephone, Output:output, DtmUpd: time.Now()})

does not update the SequenceID field, so it defaults to zero. That is causing your primary key violation. Try making the SequenceID an identity field (will automatically increment) or fix your code to determine the next sequence number and add it to your create statement