Scrapy 无法连接到 MSSQL 数据库

Scrapy wont connect to MSSQL database

固定

我的蜘蛛完全正常工作,我可以将数据导出到 JSON、CSV 和 MongoDB。但是,由于我要处理大块数据,所以我想使用 MSSQL。我浏览了 google 和 Whosebug 以找到解决方案,但尽管进行了多次尝试,但 scrapy 仍无法连接到数据库。我的兄弟是一名 SQL 开发人员,他帮助我建立了一个本地数据库,我可以用它来存储我的数据。所以我很确定数据库(非常基本)设置正确。

我目前在我的桌面上本地托管 SQL 服务器,我的桌面是它的用户名。我没有设置密码,我的数据库名为 "kaercher"。我想将数据导出到名为 "products_tb" 的 table。我给了自己完整的系统管理员访问权限,所以这应该绰绰有余了。

你们中有人使用过 MSSQL吗?

使用 pymssql 使其工作

pipelines.py

import pymssql

class KrcPipeline(object):

    def __init__(self):
        self.conn = pymssql.connect(host='DESKTOP-P1TF28R', user='sa', password='123', database='kaercher')
        self.cursor = self.conn.cursor()

    def process_item(self, item, spider):

        self.cursor.execute("INSERT INTO products_tb(productid, category, name, description, price, timestamp) VALUES (%s, %s, %s, %s, %s, %s)",
                            (item['productid'], item['category'], item['name'], item['description'], item['price'], item['timestamp']))
        self.conn.commit()

        return item

我如何找到我的驱动程序版本

for driver in pyodbc.drivers():
    print(driver)

SQL Server
SQL Server Native Client 11.0
SQL Server Native Client RDA 11.0
ODBC Driver 13 for SQL Server
ODBC Driver 17 for SQL Server
MySQL ODBC 8.0 ANSI Driver
MySQL ODBC 8.0 Unicode Driver

items.py

import scrapy


class KrcItem(scrapy.Item):
    productid=scrapy.Field()
    name=scrapy.Field()
    description=scrapy.Field()
    price=scrapy.Field()
    producttype=scrapy.Field()
    timestamp=scrapy.Field()
    category=scrapy.Field()
    pass

settings.py

ITEM_PIPELINES = {'krc.pipelines.KrcPipeline': 300}

它似乎正在通过 TCP/IP 连接,这可能未启用。使用 SQL 服务器配置管理器启用 TCP/IP 并确保实例正在侦听端口 1433。

然后,如果您要连接 Windows 用户,则需要切换到 Windows 集成身份验证,而不是 username/password。

此外,pyodbc 是连接到 SQL 服务器的推荐库。

发布的代码看起来不错。这对我有用:

import pyodbc


cnxn = pyodbc.connect(r'Driver={ODBC Driver 17 for SQL Server};Server=localhost;Database=tempdb;Trusted_Connection=yes;')

cursor = cnxn.cursor()

create_table_query = '''create table #products_tb (productid int, category varchar(20), name varchar(20), description varchar(20), price float, timestamp datetime)'''

cursor.execute(create_table_query)

insert_query = '''INSERT INTO #products_tb (productid, category, name, description, price, timestamp)
                    VALUES (?, ?, ?, ?, ?, ?);'''
item = [1,2,3,4,5]

for i in item:

    row = [i,"SomeCat","SomeName","A thing", 12.4, "20190101"]
    values = (row[0],row[1],row[2],row[3],row[4],row[5])

    cursor.execute(insert_query, values)

cnxn.commit()  

result = cursor.execute("select * from #products_tb")
rows = cursor.fetchall()

print(rows)