我编写了以下代码。我就快让它发挥作用了,我几乎可以闻到它的味道。
我正在使用mysql。连接器,tweepy, python 3.2和xampp堆栈。我正在创建一个独特的表来保存来自用户的最后3200条推文。我在一个循环中运行它,我可以得到所有的结果打印到屏幕上;绝对没问题。当我试图写入MYSQL数据库时,问题就出现了。表和列都创建得很好。
编辑:在@Yarkee和@bernie的帮助下,我编辑了以下内容:
tweet_created_date = str(tweet.created_at)
list = [tweet.id, tweet.text, tweet_created_date,
tweet.geo, tweet.contributors, tweet.coordinates,
tweet.favorited, tweet.in_reply_to_screen_name,
tweet.in_reply_to_status_id, tweet.in_reply_to_status_id_str,
tweet.in_reply_to_user_id, tweet.in_reply_to_user_id_str,
tweet.place, tweet.retweeted, tweet.retweet_count,
tweet.source, tweet.truncated]
sql = ("""INSERT INTO %(table_name)s (tweet_id, tweet_text,
tweet_created_at, tweet_geo, tweet_contributors,
tweet_coordinates, tweet_favorited,
tweet_in_reply_to_screen_name, tweet_in_reply_to_status_id,
tweet_in_reply_to_status_id_str, tweet_in_reply_to_user_id,
tweet_in_reply_to_user_id_str, tweet_place,
tweet_retweeted, tweet_retweet_count, tweet_source,
tweet_truncated) VALUES (%s, %s, %s, %s, %s, %s, %s, %s,
%s, %s, %s, %s, %s, %s, %s, %s, %s)""" % dict(table_name=table_name))
cursor.execute(sql, list)
我现在得到了TypeError: not enough arguments for format string
任何想法?
MySQLdb使用%s
参数样式,例如:(%s,%s,%s)
。它不使用?
参数样式。参考:http://mysql-python.sourceforge.net/MySQLdb.html
您需要将'%s'
转义为'%%s'
。
>>> '%(a)s, %s, %s' % dict(a='x')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> '%(a)s, %%s, %%s' % dict(a='x')
'x, %s, %s'
最终代码如下:表名是由当前unix时间值和用户屏幕名的组合单独且唯一地生成的。
tweet_list = [tweet.id, tweet.text, tweet.created_at, tweet.geo,
tweet.contributors, tweet.coordinates, tweet.favorited,
tweet.in_reply_to_screen_name, tweet.in_reply_to_status_id,
tweet.in_reply_to_status_id_str, tweet.in_reply_to_user_id,
tweet.in_reply_to_user_id_str, tweet.place, tweet.retweeted, tweet.retweet_count,
tweet.source, tweet.truncated]
sql = ("""insert into %(table_name)s (tweet_id, tweet_text,
tweet_created_at, tweet_geo, tweet_contributors, tweet_coordinates,
tweet_favorited, tweet_in_reply_to_screen_name,
tweet_in_reply_to_status_id, tweet_in_reply_to_status_id_str,
tweet_in_reply_to_user_id, tweet_in_reply_to_user_id_str,
tweet_place, tweet_retweeted, tweet_retweet_count,
tweet_source, tweet_truncated) VALUES (%%s,%%s,%%s,%%s,%%s,%%s,
%%s,%%s,%%s,%%s, %%s,%%s,%%s,%%s,%%s,%%s,%%s)"""
% dict(table_name=table_name))
cursor.execute(sql, tweet_list)
非常感谢你所有的帮助,我希望这有助于别人在未来。
使用Python 3(甚至Python 2.6或2.7),您应该利用string.format()。用一个更简单的例子来说明如何使用它:
cnx = mysql.connector.connect(database='test')
cur = cnx.cursor()
stmt = "INSERT INTO {table} (c1) VALUES (%s)".format(
table='t1'
)
data = ('ham',)
cur.execute(stmt, data)
cnx.commit()
使用format(),您不必转义%s参数标记。(请注意,我使用MySQL连接器/Python,这是在原来的问题中使用的)