Hpw tp 使用 Python 创建 SQLite3 .db 文件

问题描述 投票:0回答:1

下面的代码按原样工作,但将原始字符串(最后一条语句)更改为变量不会。

为什么?我如何让它与变量一起工作?

def create_connection(db_file):
    """ create a database connection to a SQLite database """
    conn = None
    try:
        conn = sqlite3.connect(db_file)
        print(sqlite3.version)
    except Error as e:
        print(e)
    finally:
        if conn:
            conn.close()

if __name__ == '__main__':
    create_connection(r"C:\sqlite\db\pythonsqlite.db")
python database windows sqlite creation
1个回答
0
投票

您只需定义

path
并将其传递给
create_connection
像往常一样:

import sqlite3

def create_connection(db_file):
    """ create a database connection to a SQLite database """
    conn = None
    try:
        conn = sqlite3.connect(db_file)
        print(sqlite3.version)
    except Error as e:
        print(e)
    finally:
        if conn:
            conn.close()

path = r"C:\sqlite\db\pythonsqlite.db"

if __name__ == '__main__':
    create_connection(path)
© www.soinside.com 2019 - 2024. All rights reserved.