How to insert data into database with a auto_increment key in go

huangapple go评论77阅读模式
英文:

How to insert data into database with a auto_increment key in go

问题

我有一个名为blogpost的SQL数据库表,它有一个名为id的列,设置为自动递增。现在我需要向数据库插入一个值,我使用了以下代码:

 _, err := db.Exec("Insert into blogpost (id, title, description, author) values(?,?,?)", newBlog.Title, newBlog.Description, newBlog.Author)

但是我得到了以下错误:

列计数与行1的值计数不匹配
英文:

I have a SQL database with a table named blogpost, it has a column id set to auto_increment now I have to insert a value into the database, I used the following code:

 _, err := db.Exec("Insert  into blogpost (id, title, description, author) values(?,?,?)", newBlog.Title, newBlog.Description, newBlog.Author)

but I get a following error:

Column count doesn't match value count at row 1

答案1

得分: 4

Column count doesn't match value count at row 1的错误是因为您定义了3个参数而不是4个。

您定义了id、title、description和author,总共有4列。而在提供值的地方,您只有3个values(?,?,?)

如果您已经将id设置为auto_increment,则在插入方法中不需要做任何操作,只需将其删除,如下所示:

 _, err := db.Exec("Insert into blogpost (title, description, author) values(?,?,?)", newBlog.Title, newBlog.Description, newBlog.Author)
英文:

Column count doesn't match value count at row 1 is displayed because you've defined 3 parameters and not 4.

You defined id, title, description and author which is a total of 4 columns. Whereas where you provide your values, you only have a total of 3 values(?,?,?).

If you have the id already set as auto_icnrement, you don't need to do anything in your insert method, just take it out like so:

 _, err := db.Exec("Insert  into blogpost (title, description, author) values(?,?,?)", newBlog.Title, newBlog.Description, newBlog.Author)

答案2

得分: 0

尝试从字段列表中删除id

英文:

try to remove id from fields list

huangapple
  • 本文由 发表于 2022年6月24日 18:16:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/72742523.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定