带有格式问题的Python MySQLdb TypeError

时间:2015-08-20 11:21:53

标签: python typeerror mysql-python

我是Python的新手,最近我尝试使用MySQLdb模块访问我的MySQL服务器,代码就像这样。

import MySQLdb

def convert(value):
    if value.startswith('~'):
        return value.strip('~')
    if not value:
        value='0'
    return float(value)

conn=MySQLdb.connect(host='localhost',user='root',passwd='Timeless418',
        port=3306,db='pythonsql')
curs=conn.cursor()

try:
    curs.execute('drop table food')
except Exception:   
    pass

curs.execute('''
        create table food(
        id          char(40)    primary key,
        description char(200),
        water       float,
        kcal        float,
        protein     float,
        fat         float,
        ash         float,
        carbs       float,
        fiber       float,
        sugar       float
        );
        ''')

query="insert into food values (?,?,?,?,?,?,?,?,?,?);"#10 value to formatting
for line in open('ABBREV.txt'):
    fields=line.split('^')
    vals=[convert(f) for f in fields[:10]]
    print vals
    curs.execute(query,vals)
conn.commit()
conn.close()

连接成功,但当程序试图运行时:

curs.execute(query,vals)

系统给出了这个:

['06075', 'SOUP,BF BROTH OR BOUILLON,PDR,DRY', 3.27, 213.0, 15.97, 8.89, 54.5, 17.4, 0.0, 16.71]
Traceback (most recent call last):
  File "D:\MyCodes\Python\13.2.2 import data into db.py", line 39, in <module>
    curs.execute(query,vals)
  File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 184, in execute
    query = query % db.literal(args)
TypeError: not all arguments converted during string formatting

你能告诉我为什么会发生这种情况以及如何解决这个问题吗?谢谢。

供参考:

一些原始数据(ABBREV.txt):

~06075~^~SOUP,BF BROTH OR BOUILLON,PDR,DRY~^3.27^213^15.97^8.89^54.50^17.40^0.0^16.71^60^1.00^51^320^446^26000^0.00^0.000^0.459^27.6^0.0^0.070^0.243^4.467^0.300^0.200^32^0^32^32^113.4^1.00^0^0^0^0^0^0^0^0^2.17^0.0^0^3.2^4.320^3.616^0.332^10^3.6^~1 cube~^6.0^~1 packet~^0
~06076~^~SOUP,BEEF BROTH,CUBED,DRY~^3.30^170^17.30^4.00^59.30^16.10^0.0^14.51^60^2.23^50^225^403^24000^0.21^0.000^0.386^27.6^0.0^0.200^0.240^3.300^0.300^0.200^32^0^32^32^113.4^1.00^1^0^0^0^0^0^0^0^0.00^0.0^0^0.0^1.990^1.670^0.160^4^3.6^~1 cube~^^~~^0

感谢大家的帮助,我解决了这个问题

对于查询,我将其更改为:

    query="insert into food values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);"

每个%s表示一个占位符

因为其中一个是:

['06075', 'SOUP,BF BROTH OR BOUILLON,PDR,DRY', 3.27, 213.0, 15.97, 8.89, 54.5, 17.4, 0.0, 16.71]

然后执行:

curs.execute(query,vals)

有效!我想有一种方法execute将调整vals,并填充querystr对象,它会将''添加到值,对于int或float,它只会将值放在query

再次感谢大家。

0 个答案:

没有答案