我尝试了所有可能的建议而没有结果.. 这是我的代码
class Tweet(dict):
def __init__(self, raw_tweet):
super(Tweet, self).__init__(self)
if raw_tweet and 'delete' not in raw_tweet:
self['user_id'] = raw_tweet['user']['id']
self['screen_name'] = raw_tweet['user']['screen_name']
self['timestamp'] = dateutil.parser.parse(raw_tweet[u'created_at']
).replace(tzinfo=None).isoformat()
self['hashtags'] = [x['text'] for x in raw_tweet['entities']['hashtags']]
self['text'] = raw_tweet['text']
self['geo'] = raw_tweet['geo']['coordinates'] if raw_tweet['geo'] else None
self['id'] = raw_tweet['id']
if REALTIME_DATA:
T = None
while not T:
T = Tweet(stream.next())
else:
T = Tweet(json.load(open('one_tweet.json')))
print json.dumps(T, sort_keys=True, indent=2)
userid = T.values()[0]
scrname = T.values()[1]
timestmp = T.values()[2]
hashtag = T.values()[3]
text = T.values()[4]
geo = T.values()[5]
id = T.values()[6]
data = (2)
c.execute("insert into tweets (user_id) values (%s)", (userid))
cnx.commit()
尝试了stackoverflow,python docs,mysql docs上的所有建议变体....已经花了6个小时来找出发生了什么.. 我仍然得到这个错误..
Traceback (most recent call last):
File "C:\Users\Lizard\workspace\final_project\main.py", line 69, in <module>
c.execute("insert into tweets (user_id) values (%s)", (userid))
File "C:\Python27\lib\site-packages\mysql\connector\cursor.py", line 507, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Python27\lib\site-packages\mysql\connector\connection.py", line 722, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\Python27\lib\site-packages\mysql\connector\connection.py", line 640, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s)' at line 1
发生了什么事?为什么不满意%s .. 请帮助,请不要回答类型&#34;你有没有尝试过...你读过......因为我做过......我确信这很简单,我只是在某处错过了#34;
答案 0 :(得分:2)
您应该通过添加额外的逗号来传递元组:
c.execute("insert into tweets (user_id) values (%s)", (userid,))
来自docs:
一个特殊的问题是构造包含0或1个项目的元组:语法有一些额外的怪癖来适应这些。空元组由一对空括号构成; 通过使用逗号跟随值来构造具有一个项目的元组(仅用括号括起单个值)。丑陋但有效。