Scrapy不会连接到MSSQL数据库

时间:2019-08-23 20:33:50

标签: python sql-server scrapy pymssql

已修复

我的Spider可以正常工作,可以将数据导出到JSON,CSV和MongoDB。但是,由于我将处理大量数据,因此我想使用MSSQL。我已经浏览了Google和stackoverflow以找到解决方案,但是尽管进行了许多尝试,scrapy仍无法连接到数据库。我的兄弟是SQL开发人员,他帮助我建立了一个本地数据库,可以用来存储数据。因此,我很确定数据库(非常基础的)已正确设置。

我当前正在使用其用户名在本地桌面上托管SQL Server。我尚未设置密码,我的数据库称为“ kaercher”。我想将数据导出到名为“ products_tb”的表中。我已经给了我自己完全的sysadmin访问权限,所以这应该绰绰有余。

您有任何使用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}

1 个答案:

答案 0 :(得分:0)

它似乎正在通过TCP / IP连接,可能未启用。使用SQL Server Configuration Manager启用TCP / IP并确保实例正在侦听端口1433。

如果要与Windows用户连接,则需要切换到Windows Integrated Auth,而不是用户名/密码。

也建议使用pyodbc连接到SQL Server的库。

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

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)
相关问题