Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

StructScan for insert / updates? #944

Open
nielskrijger opened this issue Sep 16, 2024 · 1 comment
Open

StructScan for insert / updates? #944

nielskrijger opened this issue Sep 16, 2024 · 1 comment

Comments

@nielskrijger
Copy link

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
Copy link

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)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants