gpt4 book ai didi

Python添加到MySQL数据库

转载 作者:行者123 更新时间:2023-11-29 08:06:10 25 4
gpt4 key购买 nike

使用 Scrapy 获取一些东西,我想将其存储在数据库中。之前从未使用过 MySQL 或 Python 做过任何事情,因此需要寻求一些帮助来了解为什么这不起作用。

这是我的代码:

from __future__ import print_function
from metacritic.items import MetacriticItem
from mysql.connector import errorcode
import mysql.connector
import json

class MetacriticPipeline(object):

DB_NAME = 'metacritic'

TABLES = {}
TABLES['titles'] = (
"CREATE TABLE `titles` ("
" `name` varchar (14) NOT NULL,"
" PRIMARY KEY (`emp_no`)"
") ENGINE=InnoDB")

cnx = mysql.connector.connect(user='root', password = 'andy')
cursor = cnx.cursor()

def process_item(self, item, spider):
if item['title']:
return item

class JsonWriterPipeline(object):

def __init__(self):
self.file = open('items.jl', 'wb')

def process_item(self, item, spider):
line = json.dumps(dict(item)) + "\n"
self.file.write(line)
return item

class WriteToDatabasePipeline(object):

def create_database(cursor):
try:
cursor.execute(
"CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'".format(DB_NAME))
except mysql.connector.Error as err:
print("Failed creating database: {}".format(err))
exit(1)

try:
cnx.database = DB_NAME
except mysql.connector.Error as err:
if err.errno == errorcode.ER_BAD_DB_ERROR:
create_database(cursor)
cnx.database = DB_NAME
else:
print(err)
exit(1)

当我尝试运行 CMD 时,出现此错误:

File "metacritic\pipelines.py", line 46, in WriteToDatabasePipeline
cnx.database = DB_NAME
NameError: name 'DB_NAME' is not defined

知道这是为什么吗?在我看来 DB_NAME 已经定义好了?我现在只想创建数据库,然后尝试添加表。感谢您的帮助

最佳答案

您正在 MetacriticPipeline 类中定义 DB_NAME,将其移动到脚本顶部(或者更好地移动到 scrapy 设置):

from __future__ import print_function
from metacritic.items import MetacriticItem
from mysql.connector import errorcode
import mysql.connector
import json

DB_NAME = 'metacritic'

class MetacriticPipeline(object):
...

关于Python添加到MySQL数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22691992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com