python执行数据库查询时类型不匹配的问题

来源:互联网 发布:石家庄关键字优化公司 编辑:程序博客网 时间:2024/06/07 11:22

今天继续完成网页信息提取的程序,发现执行到下面一行语句时会出错:

count = self.cursor.execute('update buptclub_buildiing set property_id=%s where \

building_id=%s',(self.__class__.property_code,self.__class__.building_type_code))


错误信息:

TypeError: %d format: a number is required, not str

原本以为是变量self.__class__.property_code和self.__class__.building_type_code不是int类型,与%d的不匹配,修改了很久,确保了这两个变量就是int类型。还是出错

后来直接把错误信息拿去google,看到下面的文章:

http://dwiel.net/blog/mysqldb-typeerror-d-format-a-number-is-required-not-str/

大意是说,在python里面,执行SQL语句时,所有的变量引用都应该是%s,并且不能有空格。MYSQL会自行处理,问题解决。

仍然不是很懂为什么是这样子的,对python还是略知皮毛啊


PS:

发现python中有一个模块可以查看变量类型,types

import types

assert type(id) == int