简体   繁体   中英

Golang Route for insert - PrepareContext error

I want to create route /bid/:id/:time/:offer for inserting row in database. But my struct consists of two more rows:userid and time_set. Userid is id of user that made the bid and time_set is timestamp in the moment of inserting or now(). This is my postgres repository in golang.

func (m *postgresBidRepository) CreateNewBid(ctx context.Context, id int64, time int64, offer int64) (err error) {
query := `INSERT  bid SET  id=? , time=? ,offer=? ,setAt=? ,userId=?`
stmt, err := m.Conn.PrepareContext(ctx, //WHAT HERE)

I want to take id,time and offer from header and current timestamp and userId and insert it. What should I write inside PrepareContext?? when I write id, time,offer... it returs error: cannot use id (variable of type int64) as string value in argument to m.Conn.PrepareContext

PrepareContext() except two arguments ctx and query string. You should pass the query string like this:

stmt, err := m.Conn.PrepareContext(ctx,query)

Since, you are using interpolation mode. In this mode, driver actually does three actions:

  • Prepare a statement.
  • Execute the prepared statement using given args.
  • Close the prepared statement.

That is exactly the slogan of prepared statement Prepare Once , Execute Many .

After preparing the statement you should execute it like this:

res, err := stmt.ExecContext(ctx, id, time, offer, setAt, userId)

Make sure you should pass the values for all the placeholder(?) query string else it will through an error.

In your case either you can initialize the value inside CreateNewBid() or make a external function and call it inside CreateNewBid() as per the requirement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM