错误无法创建数据库连接。/OS X/sqlite3/python3

2024-09-27 22:23:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我在连接python脚本过程中创建的sqlite3数据库时遇到一些问题。它与脚本位于同一目录中,正在创建它,但无法创建该表,因为它正在抛出:

Error! cannot create the database connection.

…行刑时

也许我遗漏了一些愚蠢的东西,我不太喜欢Python,但以下是相关的源代码,以防有人发现一些明显的问题:

import sqlite3
from sqlite3 import Error

def db_connect(fDB):
    conn = None
    try:
        conn = sqlite3.connect(fDB)
        print(sqlite3.version)
    except Error as e:
        print(e)
    finally:
        if conn:
            conn.close()

def db_create_table(conn, create_table_sql):
    try:
        c = conn.cursor()
        c.execute(create_table_sql)
    except Error as e:
        print(e)

def db():
    fDB = r"./fDB.db"
    sql_create_fits_table = """ CREATE TABLE IF NOT EXISTS fits (
                                    fHash text PRIMARY KEY,
                                    fType text NOT NULL,
                                    fFocus text NOT NULL,
                                    fSurvey text NOT NULL,
                                    fStart integer NOT NULL,
                                    fEnd integer NOT NULL,
                                    fDuration integer NOT NULL
                                ); """
    # create a database connection
    conn = db_connect(fDB)
    # create tables
    if conn is not None:
        # create fits table
        db_create_table(conn, sql_create_fits_table)
    else:
        print("Error! cannot create the database connection.")

if __name__ == '__main__': # run db operations
    db()

谢谢


Tags: textdbsqlcreatetablenoterrorconnection
2条回答

不要关闭db_connect函数中的连接,您还需要从该函数返回一个conn

def db_connect(fDB):
    conn = None
    try:
        conn = sqlite3.connect(fDB)
        print(sqlite3.version)
    except Error as e:
        print(e)

    return conn

之所以connNone,仅仅是因为db_connect没有任何return语句,所以return值默认为None。数据库连接看起来非常好,因为您没有收到错误消息

在这种情况下,我建议使用一些面向对象编程而不是函数编程

import sqlite3

class DBConnection:

    def __init__(self, dbpath):
        self.connection = sqlite3.connect(dbpath)
        self.cursor = self.connection.cursor()

    def create_table(self, query):
        self.cursor.execute(query)

def main():
    dbpath = f"./fDB.db"
    sql_create_fits_table = """
        CREATE TABLE IF NOT EXISTS fits (
            fHash text PRIMARY KEY,
            fType text NOT NULL,
            fFocus text NOT NULL,
            fSurvey text NOT NULL,
            fStart integer NOT NULL,
            fEnd integer NOT NULL,
            fDuration integer NOT NULL
        ); """
    connection = DBConnection(dbpath)
    connection.create_table(sql_create_fits_table)

if __name__ == '__main__':
    main()

相关问题 更多 >

    热门问题