英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论