繁体   English   中英

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

[英]Cannot access an sqlite3 database file with python

我正在尝试从预先存在的文件中获取配方超链接,并将它们添加到数据库中的表中。 我已经创建了数据库并给出了文件名以建立连接并将数据插入表中,但是每当我这样做时,我都会收到错误 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/来创建/链接你的数据库文件。

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

您可能需要将代码更新db = create_connection("pantry/instance/flaskr.sqlite")喜欢的东西db = create_connection("flaskr.sqlite")这应该没有任何问题工作,因为它只会在你的工作创建数据库目录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM