You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

MySQL批量插入时报column count doesn't match错误,如何解决?

问题分析与解决方案

嘿,这个问题我之前帮同事排查过!你的批量INSERT语句里,最后一条数据的字段分隔出问题了,导致这条数据的列数和前面指定的不匹配,所以数据库抛出了column count doesn't match错误。

错误点定位

看这条出问题的数据:

('Consider the lobster''David','Foster Wallace',2005,92,343)

你原本应该是把'Consider the lobster'作为title'David'作为author_fname,但不小心写成了'Consider the lobster''David'——这相当于把两个字段的内容合并成了一个字符串,导致这条数据只有5个字段(正常需要6个:title, author_fname, author_lname, released_year, stock_quantity, pages),和前面定义的列数不匹配,触发了报错。

而你单独插入的时候,应该是无意识地修正了这个分隔错误,所以能成功执行。

修正后的完整INSERT语句

把最后一条数据的分隔符改对就行,修正后的语句如下:

insert into book.books(title, author_fname,author_lname,released_year,stock_quantity,pages) 
values 
('The Namesake','Jhumpa','Lahiri',2003,32,291), 
('Norse Mythology','Neil','Gaiman',2016,43,304), 
('American Gods','Neil','Gaiman',2001,12,465), 
('Interpreter of maladies','Jhumpa','Lahiri',1996,97,198), 
('A hologram for the king: A novel','Dave','Eggers',2012,154,352), 
('The Circle','Dave','Eggers',2013,26,504), 
('Just kids','Patti','Smith',2010,55,304), 
('The Amazing adventures of kavalier & lay','Micheal','Chabon',2000,68,634), 
('A heartbreaking world of staggering genius','Dave','Eggers',2001,104,437), 
('Coraline','Neil','Gaiman',2003,100,208), 
('What we talk about when we talk about love:stories','Raymond','carver',1981,23,176), 
('where i am calling from : selected stories','Raymond','carver',1989,12,526), 
('white noise','Don','Delillo',1985,49,320), 
('Cannery row','John','Steinbeck',1945,95,181), 
('Oblivion:stories','David','Foster Wallace',2004,172,329), 
('Consider the lobster','David','Foster Wallace',2005,92,343);

批量插入的避坑小贴士

为了避免这类问题,以后批量插入时可以留意这几点:

  • 确保每一组()内的字段数量和INSERT INTO后面指定的列数完全一致
  • 如果字符串里需要包含单引号,要正确用两个单引号转义(比如标题是Consider the lobster's,要写成'Consider the lobster''s'
  • 写完后可以逐行检查逗号分隔是否正确,避免漏写或多写逗号,也避免把两个字段的内容连在一起

内容的提问来源于stack exchange,提问作者Sharath Raj

火山引擎 最新活动