typeerror:在mysql python 3中插入tweet数据时,无法调用“str”对象

xj3cbfub  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(409)

这是我在mysql中插入tweet数据的代码

import pymysql
import tweepy
import time
import json
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import pymysql.cursors

ckey= ''
csecret= ''
atoken=''
asecret=''

conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='admin1234', db='mysql')
cur = conn.cursor()

class listener(StreamListener):

 def on_data(self, data):
        all_data = json.loads(data)
        tweet = all_data["text"]
        a=0
        #username = all_data["user"]["screen_name"]

        cur.execute("INSERT INTO tweet (textt) VALUES (%s)" (tweet))
        print (tweet)
        return True

def on_error(self, status):
    print (status)

auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track = ["puasa"])

cur.close()
conn.close()

但我犯了个错误 TypeError: 'str' object is not callable 回溯错误

Traceback (most recent call last):
  File "collect-sql.py", line 40, in <module>
    twitterStream.filter(track = ["puasa"])
  File "/Users/amzar/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 450, in filter
    self._start(async)
  File "/Users/amzar/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 364, in _start
    self._run()
  File "/Users/amzar/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 297, in _run
    six.reraise(*exc_info)
  File "/Users/amzar/anaconda3/lib/python3.6/site-packages/six.py", line 693, in reraise
    raise value
  File "/Users/amzar/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 266, in _run
    self._read_loop(resp)
  File "/Users/amzar/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 327, in _read_loop
    self._data(next_status_obj)
  File "/Users/amzar/anaconda3/lib/python3.6/site-packages/tweepy/streaming.py", line 300, in _data
    if self.listener.on_data(data) is False:
  File "collect-sql.py", line 30, in on_data
    cur.execute("INSERT INTO tweet (textt) VALUES (%s)" (tweet))
TypeError: 'str' object is not callable
sxpgvts3

sxpgvts31#

您需要另外两个逗号:

cur.execute("INSERT INTO tweet (textt) VALUES (%s)", (tweet,))

第一种方法将查询字符串与参数分开,第二种方法将方括号中的值转换为1元素元组中的第一个元素(如果只使用单个字符串而不是元组,假设只有一个参数,这实际上是可行的,但从外观上看,这并不是官方支持的)。
但是你在评论中提到的这个错误:

UnicodeEncodeError: 'latin-1' codec can't encode character '\u201c' in position 97: ordinal not in range(256)

表示您正试图将包含扩展字符集中字符的unicode文本解释为 latin-1 .
如果该字段已在内部定义为unicode(在mysql数据库中),则可能需要指定连接时使用的字符集,例如:

conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='admin1234', db='mysql', use_unicode=True, charset="utf8")

如果mysql中的字段还不是utf-8,那么我建议您更改或重新定义数据库,以便在此列中使用unicode字符se tf。
https://dev.mysql.com/doc/refman/8.0/en/charset-mysql.html

相关问题