MOBI BOOT CAMP CORP. logoLearning Buddy
  • SIGN IN
  • SQL & NoSQL Databases
  • 1. Relational Database Fundamentals
  • 2. SQL: Basic Data Manipulation (DML)
  • 3. SQL: Filtering and Sorting
  • 4. SQL: Aggregation and Relations
  • 5. SQL: Schema Management (DDL)
  • 6. Python and SQL
    • Using the sqlite3 package
    • Accessing Metainformation
  • 7. NoSQL Databases
  • References

Python sqlite3 package

Python has a built-in package called sqlite3 that implements SQLite.

Basic Workflow

  1. Connect to a database: A Connection object represents the database.

    import sqlite3
    conn = sqlite3.connect('example.db')
    
  2. Create a cursor: A Cursor object is used to interact with the database.

    c = conn.cursor()
    
  3. Execute SQL commands:

    c.execute('''CREATE TABLE stocks
                 (date text, trans text, symbol text, qty real, price real)''')
    
  4. Insert data:

    c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
    

    To insert many records, use executemany:

    purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
                 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
                 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
                ]
    c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
    

    Using ? as a placeholder is important to prevent SQL injection attacks.

  5. Commit the changes:

    conn.commit()
    
  6. Query the database:

    for row in c.execute('SELECT * FROM stocks ORDER BY price'):
        print(row)
    
  7. Close the connection:

    conn.close()
    

Important point: Unlike many other RDBMSs, SQLite does not allow multiple connections to the same database at the same time.

Privacy Policy | Terms & Conditions