簡體   English   中英

Scrapy不會連接到MSSQL數據庫

[英]Scrapy wont connect to MSSQL database

固定

我的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}

它似乎正在通過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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM