擅长:python、mysql、java
<p>不要将tweet编码为UTF-8,也不要使用字符串格式来创建查询。在</p>
<p>请改用SQL参数:</p>
<pre><code>tweetid = tweet['id_str']
userid = tweet['user']['id_str']
text = tweet['text']
cur.execute(
"""INSERT INTO twitterfeeeds(tweet_id, user_id,body,status) VALUES (%s, %s, %s, '0')""",
(tweetid, userid, text))
</code></pre>
<p>是的,上面的代码和您的代码有区别;<code>tweetid</code>、<code>userid</code>和{<cd3>}值都作为一个单独的参数(元组)传递给<code>cursor.execute()</code>方法。在</p>
<p>游标负责处理要插入数据库的数据的正确转义。这样可以避免SQL注入攻击(带有<code>;DROP TABLE twitterfeeeds</code>的tweet会立即破坏数据库),并启用查询计划优化。在</p>
<p>这一切都需要您配置数据库连接以支持Unicode数据;在连接上将字符集设置为UTF-8:</p>
^{pr2}$
<p>或者更好的方法是,将数据库配置为使用UTF8MB4字符集(MySQL使用的UTF-8版本无法处理表情符号或U+FFFF之外的其他代码点):</p>
<pre><code># Note, no characterset specified
con = MySQLdb.connect(host="localhost", user='root', password='', db='')
cursor = con.cursor()
cursor.execute('SET NAMES utf8mb4')
cursor.execute('SET CHARACTER SET utf8mb4')
cursor.execute('SET character_set_connection=utf8mb4')
</code></pre>