yayu
yayu

Reputation: 8088

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

I wrote a Python script which initializes an empty database if it doesn't exist.

import os

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

# rest of the script...

Can I do this in a more Pythonic fashion, with a try-except, or is this kind of code acceptable?

Upvotes: 27

Views: 42452

Answers (4)

Serge Stroobandt
Serge Stroobandt

Reputation: 31518

Create directory path, database file and table

Here is a recipe to create the directory path, database file and table when necessary. If these already exist, the script will overwrite nothing and simply use what is at hand.

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()

Upvotes: 7

zenpoy
zenpoy

Reputation: 20126

I think you can do it like this:

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

This should connect to your database and create it in case that it doesn't exist. I'm not sure this is the most pythonic way, but it does use the sqlite3 module instead of the sqlite3 command.

Upvotes: 49

Aaron Hall
Aaron Hall

Reputation: 395045

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

The most Pythonic way to do this is to use the context manager:

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)

In a python shell this echoes for me:

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

To ensure you have a tempfile path that works across platforms, use tempfile.gettempdir:

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

Upvotes: 7

Jon Clements
Jon Clements

Reputation: 142156

sqlite3.connect will attempt to create a database if it doesn't exist - so the only way to tell if one does exist is to try to open it and catch an IOError. Then to create a blank database, just connect using the sqlite3 module.

import sqlite3

try:
    open('idonotexist')
    print 'Database already exists!'
except IOError as e:
    if e.args == 2: # No such file or directory
        blank_db = sqlite3.connect('idontexist')
        print 'Blank database created'
    else: # permission denied or something else?
        print e

Of course, you may still have to do something with os.makedirs depending on if the structure already exists.

Upvotes: 5

Related Questions