无法使用 python 访问 sqlite3 数据库文件

Cannot access an sqlite3 database file with python

我正在尝试从预先存在的文件中获取食谱超链接并将它们添加到数据库中的 table。我已经创建了数据库并给出了文件名以建立连接并将数据插入 table 但每当我这样做时我都会收到错误 sqlite3.OperationalError:无法打开数据库文件。 这是我的代码:

import bs4, os, requests, time
import sqlite3
from flask import current_app, g

def create_connection(db_file):
    db = sqlite3.connect(db_file)
    c = db.cursor()

    return db


def get_html():
    '''
    Get the BBC Food sitemap and save it to a local file.
    '''
    page = None
    db = create_connection("pantry/instance/flaskr.sqlite")
    for attempt in range(1, 4):
        print("line 40")
        page = requests.get('http://www.bbc.co.uk/food/sitemap.xml')
        try:
            page.raise_for_status()
            break
        except requests.RequestException:
            time.sleep(attempt * 10)

    if not page:
        raise Exception('Failed to get sitemap.xml')

    sitemap = bs4.BeautifulSoup(page.text, 'html.parser')
    # Write the recipe urls to a text file
    print("line 53")
    for line in sitemap.find_all('loc'):
        for string in line.stripped_strings:
            if string.startswith('https://www.bbc.co.uk/food/recipes/'):
                print("line 57")
                recipeUrl = string
                if (
                        db.execute("SELECT recipeID FROM recipe WHERE weblink = ?", (recipeUrl,)).fetchone()
                        is not None
                ):
                    error = "recipe weblink {0} is already inputted.".format(recipeUrl)
                if error is None:
                    db.execute(
                        'INSERT INTO recipe (weblink) VALUES (?)',
                        recipeUrl
                    )
                    db.commit()
    db.close()

错误信息:

Traceback (most recent call last):
File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm 2019.2.2\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm 2019.2.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/Eva Morris/PycharmProjects/pantry/flaskr/BBCscraper/scraperecipes.py", line 161, in <module>
    get_html()
  File "C:/Users/Eva Morris/PycharmProjects/pantry/flaskr/BBCscraper/scraperecipes.py", line 34, in get_html
    db = create_connection("pantry/instance/flaskr.sqlite")
  File "C:/Users/Eva Morris/PycharmProjects/pantry/flaskr/BBCscraper/scraperecipes.py", line 23, in create_connection
    db = sqlite3.connect(db_file)
sqlite3.OperationalError: unable to open database file

根据控制台错误报告,您的 .py 文件位于:C:/Users/Eva Morris/PycharmProjects/pantry/flaskr/BBCscraper/scraperecipes.py".

在您的代码中,您使用相对路径将数据库目录设置为:pantry/instance/flaskr.sqlite.

这意味着 python 正在寻找目录:C:/Users/Eva Morris/PycharmProjects/pantry/flaskr/BBCscraper/pantry/instance/ 到 create/link 您的数据库文件。

如果该目录不是预先存在的目录,sqlite3.connect 将无法创建您的数据库 flaskr.sqlite

您可能需要将代码 db = create_connection("pantry/instance/flaskr.sqlite") 更新为类似 db = create_connection("flaskr.sqlite") 的代码,这样应该可以正常工作,因为它只会在您的工作目录中创建数据库。