jmoiron / sqlx

general purpose extensions to golang's database/sql
http://jmoiron.github.io/sqlx/
MIT License
16.3k stars 1.09k forks source link

StructScan for insert / updates? #944

Open nielskrijger opened 2 months ago

nielskrijger commented 2 months ago

Am I correct in saying there is no StructScan equivalent for insert/updates?

If not, does anyone know about a lib providing this for PGQ? (I'm not talking about ORM's which all seem to include query bulders, migrators etc)

rahmatismail commented 2 months ago

sqlx version: v1.3.5

You can use NamedExec / NamedExecContext. It uses bindNamedMapper to map the struct tag into your query. Although they are not 100% equivalent with StructScan because you need to state struct tag value on the query

type (
    Consultants struct {
        ConsultantName string `db:"ConsultantName"`
        Technology     string `db:"Technology"`
        HourlyRate     int64  `db:"HourlyRate"`
    }
)

func insertWithStruct() {
    db, err := sql.Open("yourDriverName", "user:password@tcp(127.0.0.1:3306)/tablename")
    if err != nil {
        log.Fatalln(err)
    }
    dbx := sqlx.NewDb(db, "yourDriverName")

    data := Consultants{
        ConsultantName: "name-go",
        Technology:     "go",
        HourlyRate:     1234,
    }
    res, err := dbx.NamedExec("insert into Consultants (ConsultantName, Technology, HourlyRate) values (:ConsultantName, :Technology, :HourlyRate)", data)
    if err != nil {
        log.Fatalln(err)
    }

    lastInsertID, err := res.LastInsertId()
    if err != nil {
        log.Fatalln(err)
    }
    rowsAffected, err := res.RowsAffected()
    if err != nil {
        log.Fatalln(err)
    }
    fmt.Printf("%d %d\n", lastInsertID, rowsAffected)
}