(Python 3.6)TypeError:无法将字节连接到元组

时间:2017-06-28 04:41:43

标签: python mysql concat

我正在尝试将已删除的项目('标题')插入到mySQL数据库中。

这是我的spider.py文件的片段,它标题为' title'含量:

#get more details
def parse_detail_page(self, response):
    item = response.meta["item"]

    #title
    title = response.xpath(".//*[@id='titletextonly']/text()").extract()[0]
    item["title"] = title

    return item

这是我的pipelines.py文件:

import pymysql.cursors

class mySQLTest(object):

    def __init__(self):
        self.conn = pymysql.connect(host='localhost',
                             user='root',
                             password='',
                             db='testDB',
                             charset='utf8mb4',
                          cursorclass=pymysql.cursors.DictCursor)
        self.cursor = self.conn.cursor()


    def process_item (self, item, spider):
        sql = "INSERT INTO items (title) VALUES (%s)", (item['title'])
        self.cursor.execute(sql)
        self.conn.commit()

        return item

我遇到了以下错误:

    Traceback (most recent call last):
  File "/Users/venv1/lib/python3.6/site-packages/twisted/internet/defer.py", line 653, in _runCallbacks
    current.result = callback(current.result, *args, **kw)
  File "/Users/venv1/tutorial/tutorial/pipelines.py", line 31, in process_item
    self.cursor.execute(sql)
  File "/Users/venv1/lib/python3.6/site-packages/pymysql/cursors.py", line 166, in execute
    result = self._query(query)
  File "/Users/sandysu/PyCharmProjects/venv1/lib/python3.6/site-packages/pymysql/cursors.py", line 322, in _query
    conn.query(q)
  File "/Users/venv1/lib/python3.6/site-packages/pymysql/connections.py", line 855, in query
    self._execute_command(COMMAND.COM_QUERY, sql)
  File "/Users/venv1/lib/python3.6/site-packages/pymysql/connections.py", line 1091, in _execute_command
    packet = prelude + sql[:packet_size-1]
TypeError: can't concat bytes to tuple

这个 TypeError:无法将字节连接到元组是什么意思?该如何修复?

1 个答案:

答案 0 :(得分:0)

这是最终能够将数据插入数据库的语法:

def process_item (self, item, spider):
    sql = "INSERT INTO items (title) VALUES (%s)"
    data = item['title']

    self.cursor.execute(sql, data)
    self.conn.commit()

    return item