您的位置:首页 > 编程语言 > Python开发

python mysql插入数据遇到的错误

2018-06-21 10:11 525 查看

1.数据插入的时候报错:not enough arguments for format string,大概意思就是说没有足够的参数格式化字符串。

我的数据库插入方法是这样的

def add_data(self,data_dic):
tables = 'user'
keys = ','.join(data_dic.keys())
values = ','.join(['%s'] * len(data_dic))
sql =f'INSERT INTO {tables} ({keys}) VALUES({values}) ON DUPLICATE KEY UPDATE '
update = ','.join([f"{k}='{v}'" for k,v in data_dic.items()])
sql += update
try:
if self.cursor.execute(sql, tuple(data_dic.values())):
print('ok')
self.conn.commit()
except Exception as e:
print(e.args)
self.conn.rollback()
self.conn.close()

  通过调试我得知程序在执行cursor.execute的时候报了该错误。

为了进一步了解原因,我找到了关于实现execute的方法:

def mogrify(self, query, args=None):
"""
Returns the exact string that is sent to the database by calling the
execute() method.

This method follows the extension to the DB API 2.0 followed by Psycopg.
"""
conn = self._get_db()
if PY2:  # Use bytes on Python 2 always
query = self._ensure_bytes(query, encoding=conn.encoding)

if args is not None:
query = query % self._escape_args(args, conn)
return query

  通过上面的方法可以的得知,关键的一句话是

query = query % self._escape_args(args, conn)

 我要插入最后一个字段中有其中一段文字

厨房和体育健身用品等进口关税平均税率由 15.9%降至7.2%

  因为%的原因出错了,所以我尝试这把上面方法修改成下面的方式 使用format去格式化字符串

def add_data(self,data_dic):
tables = 'user'
keys = ','.join(data_dic.keys())
values = ','.join(['%s'] * len(data_dic))
sql ='INSERT INTO {tables} ({keys}) VALUES({values}) ON DUPLICATE KEY UPDATE '.format(tables=tables,keys=keys,values=values)
update = ','.join(["{key}=%s".format(key=key) for key in data_dic])
sql += update
try:
if self.cursor.execute(sql,tuple(data_dic.values())*2):
print('ok')
self.conn.commit()
except Exception as e:
print(e.args)
self.conn.rollback()
self.conn.close()

  

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: