{"id":22942251,"url":"https://github.com/imshakil/python-sqlite-practice","last_synced_at":"2026-05-02T19:34:19.315Z","repository":{"id":115377308,"uuid":"288013956","full_name":"imShakil/python-sqlite-practice","owner":"imShakil","description":"Python SQLite cheat sheet","archived":false,"fork":false,"pushed_at":"2025-03-30T04:51:42.000Z","size":33,"stargazers_count":6,"open_issues_count":0,"forks_count":3,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-30T05:23:42.514Z","etag":null,"topics":["cheat-sheet","python","python-3","python3","sqlite","sqlite-cheat-sheet","sqlite-database","sqlite3"],"latest_commit_sha":null,"homepage":"https://mobarakit.com/python-sqlite-practice/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/imShakil.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-08-16T19:50:44.000Z","updated_at":"2025-03-30T04:51:45.000Z","dependencies_parsed_at":"2023-03-10T03:00:15.461Z","dependency_job_id":null,"html_url":"https://github.com/imShakil/python-sqlite-practice","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/imShakil/python-sqlite-practice","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/imShakil%2Fpython-sqlite-practice","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/imShakil%2Fpython-sqlite-practice/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/imShakil%2Fpython-sqlite-practice/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/imShakil%2Fpython-sqlite-practice/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/imShakil","download_url":"https://codeload.github.com/imShakil/python-sqlite-practice/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/imShakil%2Fpython-sqlite-practice/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32547650,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-02T19:18:06.202Z","status":"ssl_error","status_checked_at":"2026-05-02T19:16:21.335Z","response_time":132,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cheat-sheet","python","python-3","python3","sqlite","sqlite-cheat-sheet","sqlite-database","sqlite3"],"created_at":"2024-12-14T13:47:11.670Z","updated_at":"2026-05-02T19:34:19.294Z","avatar_url":"https://github.com/imShakil.png","language":"Python","readme":"# Python SQLite Cheat-Sheet\n[![GitHub stars](https://img.shields.io/github/stars/imshakil/python-sqlite-practice)](https://github.com/imshakil/python-sqlite-practice/stargazers)\n[![GitHub forks](https://img.shields.io/github/forks/imshakil/python-sqlite-practice)](https://github.com/imshakil/python-sqlite-practice/network)\n[![GitHub issues](https://img.shields.io/github/issues/imshakil/python-sqlite-practice)](https://github.com/imshakil/python-sqlite-practice/issues)\n[![GitHub License](https://img.shields.io/github/license/imShakil/python-sqlite-practice)](https://github.com/imshakil/python-sqlite-practice)\n[![Twitter](https://img.shields.io/twitter/url?style=social\u0026url=https%3A%2F%2Fgithub.com%2Fimshakil%2Fpython-sqlite-practice)](https://twitter.com/intent/tweet?text=Wow:\u0026url=https%3A%2F%2Fgithub.com%2Fimshakil%2Fpython-sqlite-practice)\n\n\u003c!-- [![HitCount](https://hits.dwyl.com/imshakil/python-sqlite-practice.svg?style=flat-square)](http://hits.dwyl.com/imshakil/python-sqlite-practice)\n#[![HitCount](https://hits.dwyl.com/imshakil/python-sqlite-practice.svg?style=flat-square\u0026show=unique)](http://hits.dwyl.com/imshakil/python-sqlite-practice)\n--\u003e\n\nSQLite3 is a very easy to use database engine. It is self-contained, serverless, zero-configuration and transactional.\nIt is very fast and lightweight, and the entire database is stored in a single disk file. It is used in a lot of\napplications as internal data storage. The Python Standard Library includes a module called \"sqlite3\" intended for\nworking with this database. This module is a SQL interface compliant with the DB-API 2.0 specification.\n\n**Table of Contents**\n- [SQLite Python Module](#import-sqlite-module)\n- [Connect and Creating Database](#connect-and-create-database)\n- [CREATE and DROP TABLE](#creating-create-and-deleting-drop-tables)\n- [INSERT INTO TABLE](#inserting-insert-data-into-the-database)\n- [SELECT FROM (data retrieving)](#retrieving-data-select-from-database)\n- [UPDATE and DELETE FROM](#updating-update-and-deleting-delete-data)\n- [SQLite Transaction](#using-sqlite-transactions)\n- [Handling SQLite Exceptions](#sqlite-database-exceptions)\n- [SQLite Row Factory](#sqlite-row-factory-and-data-types)\n\n## Import SQLite Module\n\n```python\nimport random\nimport sqlite3\n```\n\n\n## Connect and Create Database \nWe use the function ```sqlite3.connect``` to connect to the database. We can use the argument ```:memory:``` to create \na temporary DB in the RAM or pass the name of a file to open or create it.\n\n\n```python\n# create database in memory\n# db = sqlite3.connect(':memory:')\n\n# create database into directory\ndb = sqlite3.connect(\"./data/test.db\")\n\n# get a cursor object\ncursor = db.cursor()\n```\n\n\n## Creating (```CREATE```) and Deleting (```DROP```) Tables\nIn order to make any operation with the database we need to get a cursor object and pass the SQL statements to the \ncursor object to execute them. Finally it is necessary to commit the changes. We are going to create a users table with \nname, phone, email and password columns.\n\n\n```python\n# DROP TABLE\ncursor.execute(\"\"\"DROP TABLE IF EXISTS users\"\"\")\n\n# CREATE TABLE\ncursor.execute(\n    \"\"\"CREATE TABLE IF NOT EXISTS users(\n                    id INTEGER PRIMARY KEY,\n                    name TEXT,\n                    phone TEXT,\n                    email TEXT unique,\n                    password TEXT\n            )\"\"\"\n)\n\ndb.commit()\n```\n\n## Inserting (```INSERT```) Data into the Database\nTo insert data we use the cursor to execute the query. If you need values from Python variables it is recommended \nto use the \"?\" placeholder. Never use string operations or concatenation to make your queries because is very insecure.\nIn this example we are going to insert two users in the database, their information is stored in python variables.\n\n```python\nname = 'Halim'\nphone = \"01234567890\"\nemail = \"halim@email.com\"\npassword = \"ha1234\"\ncursor.execute(\n    \"\"\"INSERT INTO users(name, phone, email, password) VALUES (?,?,?,?)\"\"\",\n    (name, phone, email, password),\n)\ndb.commit()\n```\n\n\nThe values of the Python variables are passed inside a tuple. \nAnother way to do this is passing a dictionary using the ```:key name``` placeholder:\n\n```python\nname = \"Alim\"\nphone = \"01234567890\"\nemail = \"alim@email.com\"\npassword = \"al1234\"\ncursor.execute(\n    \"\"\"INSERT INTO users(name, phone, email, password) VALUES (:name, :phone, :email, :password)\"\"\",\n    {\n        \"name\": name,\n        \"phone\": phone,\n        \"email\": email,\n        \"password\": password,\n    },\n)\ndb.commit()\n\n# use list of users for inserting multiple user info\nusers = [\n    (\n        \"Name \" + str(i),\n        str(random.randint(10000000, 1000000000)),\n        \"name\" + str(i) + \"@email.com\",\n        str(random.randint(10000, 90000)),\n    )\n    for i in range(10)\n]\n\ncursor.executemany(\n    \"\"\"INSERT INTO users(name, phone, email, password) VALUES (?, ?, ?, ?)\"\"\", users\n)\ndb.commit()\n```\n\n### Get Last Row ID\n\nIf you need to get the id of the row you just inserted use ```lastrowid```\n\n```python\nprint(f\"last row id: {cursor.lastrowid}\")\n```\n\n## Retrieving Data (```SELECT```) from Database\nTo retrieve data, execute the query against the cursor object and then use ```fetchone()``` to retrieve a single row or \n```fetchall()``` to retrieve all the rows and ```fetchmany()``` to retrieve a particular number or rows.\n(note: retrieve rows fetched as a list where each row as a tuple)\n\n```python\ncursor.execute(\"\"\"SELECT name, phone, email FROM users\"\"\")\nuser1 = cursor.fetchone()\nprint(user1)\n\nuser_many = cursor.fetchmany(5)\nprint(user_many)\n\nuser_all = cursor.fetchall()\nprint(user_all)\n```\n\nThe cursor object works as an iterator, invoking ```fetchall()``` automatically\n\n```python\ncursor.execute(\"\"\"SELECT name, email, phone FROM users\"\"\")\nfor row in cursor:\n    print(f\"name: {row[0]} email: {row[1]} phone: {row[2]}\")\n```\n\nTo retrieve data with conditions, use again the \"?\" placeholder\n\n```python\nuser_id = 5\ncursor.execute(\"\"\"SELECT name, email, phone FROM users WHERE id=?\"\"\", (user_id,))\nprint(cursor.fetchone())\n```\n\n## Updating (```UPDATE```) and Deleting (```DELETE```) Data\nThe procedure to update or delete data is the same as inserting data\n\n```python\n# update user phone with id = 5\ncursor.execute(\"\"\"UPDATE users SET phone = ? WHERE id = ?\"\"\", (\"01710567890\", user_id))\ndb.commit()\n\n# delete user row with id = 8\ncursor.execute(\"\"\"DELETE FROM users WHERE id = ?\"\"\", (8,))\ndb.commit()\n```\n\n## Using SQLite Transactions\nTransactions are an useful property of the database systems. It ensures the atomicity of the Database. Use ```commit()``` \nmethod to save the changes and ```rollback()``` method to roll back any change to the database since the last call to commit.\n\n```python\n# update user phone with id = 5\ncursor.execute(\"\"\"UPDATE users SET phone = ? WHERE id = ?\"\"\", (\"01712567890\", user_id))\ndb.rollback()\n```\n\nPlease remember to always call commit to save the changes. If you close the connection using close or the connection to \nthe file is lost (maybe the program finishes unexpectedly), not committed changes will be lost.\n\n\n## SQLite Database Exceptions\nFor best practices always surround the database operations with a try clause or a context manager.\n\n```python\ntry:\n    # create or connect database\n    db = sqlite3.connect(\"./data/test.db\")\n\n    # get a cursor object\n    cursor = db.cursor()\n\n    # check if a table 'users' does exist or not and create it\n    cursor.execute(\n        \"\"\"CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY, name TEXT, phone TEXT, email TEXT unique, password TEXT)\"\"\"\n    )\n    # commit to save the changes\n    db.commit()\n\nexcept Exception as e:\n    # rollback any change if something goes wrong\n    db.rollback()\n    raise e\nfinally:\n    db.close()\n```\n\n### Check Integrity Error\nWe can use the Connection object as context manager to automatically commit or rollback transactions\n\n```python\nname1 = \"Mobarak\"\nphone1 = \"3366858\"\nemail1 = \"imshakil@github.com\"\n# A very secure password\npassword1 = \"12345\"\ntry:\n    db = sqlite3.connect(\"./data/test.db\")\n    with db:\n        db.execute(\n            \"\"\"INSERT INTO users (name, phone, email, password) VALUES (?, ?, ?, ?)\"\"\",\n            (name1, phone1, email1, password1),\n        )\nexcept sqlite3.IntegrityError:\n    print(\"Data already exists\")\nfinally:\n    db.close()\n```\n\nIn the example above if the insert statement raises an exception, the transaction will be rolled back and the message \ngets printed; otherwise the transaction will be committed. Please note that we call execute on the db object, not the \ncursor object.\n\n\n## SQLite Row Factory and Data Types \nThe following table shows the relation between SQLite datatypes and Python datatypes:\n\n- None type is converted to NULL\n- int type is converted to INTEGER\n- float type is converted to REAL\n- str type is converted to TEXT\n- bytes type is converted to BLOB\n\nThe row factory class ```sqlite3.Row``` is used to access the columns of a query by name instead of by index.\n\n```python\ndb = sqlite3.connect(\"./data/test.db\")\ndb.row_factory = sqlite3.Row\ncursor = db.cursor()\ncursor.execute(\"\"\"SELECT name, email, phone FROM users\"\"\")\nfor row in cursor:\n    print(f\"name : {row[0]}, email: {row[1]}, phone: {row[2]}\")\n\n# close database connection\ndb.close()\n```\n\n\u003e Thanks to Andres Torres for awesome blog post \u003cbr\u003e \n\u003e Source: https://www.pythoncentral.io/introduction-to-sqlite-in-python/\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fimshakil%2Fpython-sqlite-practice","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fimshakil%2Fpython-sqlite-practice","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fimshakil%2Fpython-sqlite-practice/lists"}