Hpw tp Create SQLite3 .db file with Python

116 Views Asked by At

The below code works as-is, but changing the raw string (last statement) to a variable does not.

Why? How do I make it work with a variable?

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")
1

There are 1 best solutions below

2
mimak On

You simply define path and pass it into create_connection as usual:

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)