Home > Back-end >  How to insert data into database with a auto_increment key in go
How to insert data into database with a auto_increment key in go

Time:06-24

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

CodePudding user response:

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)

CodePudding user response:

try to remove id from fields list

  • Related