在msyql数据库中存储数据时,程序出现了如下报错:
打印存储的数据类型发现数据类型有错误,将数据转为str类型就可以了。。。
解决思路:
在初入数据库学习时,出现这个报错还是有些懵的,于是改了捕获异常,发现存储数据函数有问题。从报错中可以看出是有跟'自营店'类似的数据有关系的,于是,查看了自己的数据库的插入语句:
sql = "insert into dang_datas7(title_first, title_second, title_third, book_name, book_now_price, book_pre_price, book_author, book_publishing_house, book_business) values (%s,%s,%s,%s,%s,%s,%s,%s,%s)"
params = [[str(title_first), str(title_second), str(title_third),
str(book_name), str(book_now_price), str(book_pre_price),
str(book_author), str(book_publishing_house),
str(book_business)]]
cursor.executemany(sql, params)
db.commit()
发现并没有什么问题,于是又检查了下数据库建表语法:
create table dang_datas7
(
id int auto_increment
primary key,
title_first varchar(3000) null,
title_second varchar(3000) null,
title_third varchar(3000) null,
book_name varchar(3000) null,
book_now_price varchar(3000) null,
book_pre_price text null,
book_author text null,
book_publishing_house text null,
book_business text null
)
charset = utf8mb3;
desc dang_datas7;
同样发现并没有什么大问题,都是支持字符串类型的数据储存的。于是还是先看一下插入语句的具体类型:
# 查看存储数据的类型
print(type(book_name),type(book_now_price),type(book_pre_price),type(book_author),
type(book_publishing_house),type(book_business),)
发现有些端倪,有个不一样的数据类型混了进来,
<class 'lxml.etree._ElementUnicodeResult'> <class 'lxml.etree._ElementUnicodeResult'>
<class 'lxml.etree._ElementUnicodeResult'> <class 'str'> <class 'list'> <class 'str'>
经检查发现,上述错误是存储的数据类型有问题,报错中有以下几种数据类型如:<class 'lxml.etree._ElementUnicodeResult'>、list、str,但是在我们的sql语法中只有varchar和text两种数据类型才可以储存,所以,我们将list转化为str类型即可。同样的以防出现同样的错误,我们可以将params中所有的类型改为str字符串类型。如下:
params = [[str(title_first), str(title_second), str(title_third),
str(book_name), str(book_now_price), str(book_pre_price),
str(book_author), str(book_publishing_house),
str(book_business)]]
再执行,发现没有此类报错出现了,这样我们就成功的解决了报错中提示的语法错误的问题了。
但为了后面解决数据库报错,还是建议打印出来插入的数据及语法,以方便检查具体报错内容。
print(sql, params)
像我这种出现了空列表([])的数据出现,于是将其转为字符串就不会出现了,但为了数据的精确性,尽量检查自己的抓取逻辑或加入判断替换为其他数据。
若仍然报错,可通过以下几个方面进行检查:
1、SQL语句中的字段名是否和数据库表结构中的字段名一致;
2、数据库表结构中的字段类型是否和传入的参数类型一致;
3、传入的参数是否有空值或非法值,例如长度超过字段定义的最大长度等;
4、数据库连接是否正常,以及是否有权限执行插入操作。
- 数据 syntax 39 quot your39 syntax sqlsyntaxerrorexception your 数据syntax 39 quot syntax your corresponds the syntax sqlsyntaxerrorexception your corresponds 脚本unexpected 39 syntax 39 quot attributeerror attribute quot lacalhost the 39 operationalerror quot 39 content quot configuration sqlserver 39 number-of-buckets-specified 39 quot json_extract