英文:
Golang Route for insert - PrepareContext error
问题
我想创建一个路由 /bid/:id/:time/:offer 来向数据库插入一行数据。但是我的结构体还包括两个字段:userid 和 time_set。Userid 是进行竞标的用户的 ID,time_set 是插入时的时间戳或 now()。这是我在 Golang 中的 PostgreSQL 存储库。
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, query)
我想从请求头中获取 id、time 和 offer,以及当前时间戳和 userId,并将其插入数据库。在 PrepareContext 中应该写什么?当我写 id、time、offer 时,它会返回错误:
cannot use id (variable of type int64) as string value in argument to m.Conn.PrepareContext
英文:
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
答案1
得分: 1
PrepareContext()
函数接受两个参数ctx和查询字符串query。你应该像这样传递查询字符串:
stmt, err := m.Conn.PrepareContext(ctx, query)
由于你正在使用插值模式,驱动程序实际上执行了三个操作:
- 准备一个语句。
- 使用给定的参数执行准备好的语句。
- 关闭准备好的语句。
这正是准备语句的口号:“准备一次,执行多次”。
在准备好语句之后,你应该像这样执行它:
res, err := stmt.ExecContext(ctx, id, time, offer, setAt, userId)
确保为所有的占位符(?)查询字符串传递值,否则会抛出错误。
在你的情况下,你可以在CreateNewBid()
函数内部初始化值,或者根据需求创建一个外部函数,并在CreateNewBid()
函数内部调用它。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论