Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 218
yayu Avatar asked Jul 22 '12 09:07

yayu


People also ask

Why is SQLite not good for production?

The biggest problem with using SQLite in production is disaster recovery. If your server dies, so does your data. That's… not good. Other database servers have replication so they can stream database changes to another server in case one goes down.

Is sqlite3 default in Python?

SQLite3 can be integrated with Python using sqlite3 module, which was written by Gerhard Haring. It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249. You do not need to install this module separately because it is shipped by default along with Python version 2.5. x onwards.


Video Answer


2 Answers

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.

like image 174
zenpoy Avatar answered Sep 28 '22 02:09

zenpoy


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:
    ...
like image 39
Russia Must Remove Putin Avatar answered Sep 28 '22 01:09

Russia Must Remove Putin