使其成为Pythonic:如果sqlite3数据库不存在,则创建它?

2024-06-28 18:55:12 发布

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

我写了一个Python脚本,如果一个空数据库不存在,它就会初始化它。

import os

if not os.path.exists('Database'):
    os.makedirs('Database')
    os.system('sqlite3 Database/testDB.db ";"')

# rest of the script...

我可以用一种更像Python的方式来做这个,除了试试,或者这种代码可以接受吗?


Tags: pathimport脚本rest数据库dbifos
3条回答

Making it Pythonic: create a sqlite3 database if it doesn't exist?

最有效的方法是使用上下文管理器:

import sqlite3

# if we error, we rollback automatically, else commit!
with sqlite3.connect('/Temp/testDB.db') as conn:
    cursor = conn.cursor()
    cursor.execute('SELECT SQLITE_VERSION()')
    data = cursor.fetchone()
    print('SQLite version:', data)

在一个python shell中,这对我来说是一个回声:

<sqlite3.Cursor object at 0x0CCAD4D0>
SQLite version: (u'3.5.9',)

要确保具有跨平台工作的tempfile路径,请使用tempfile.gettempdir

import tempfile
with sqlite3.connect(tempfile.gettempdir() + '/testDB.db') as conn:
    ...

我想你可以这样做:

import sqlite3
conn = sqlite3.connect('Database/testDB.db')

这应该连接到您的数据库,并在它不存在的情况下创建它。我不确定这是最pythonic的方式,但它确实使用了sqlite3模块而不是sqlite3命令。

创建目录路径、数据库文件和表

下面是创建目录路径、数据库文件和表的方法 必要时。如果这些已经存在,脚本将不覆盖任何内容,只使用手头的内容。

import os
import sqlite3

data_path = './really/deep/data/path/'
filename = 'whatever'

os.makedirs(data_path, exist_ok=True)

db = sqlite3.connect(data_path + filename + '.sqlite3')
db.execute('CREATE TABLE IF NOT EXISTS TableName (id INTEGER PRIMARY KEY, quantity INTEGER)')
db.close()

相关问题 更多 >