From 8d51ae48ab084284681d597b436be2112650a3b9 Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Tue, 25 Jan 2022 17:35:26 -0800 Subject: [PATCH] Getting started section for Python library, closes #387 --- docs/python-api.rst | 59 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/docs/python-api.rst b/docs/python-api.rst index 6b0d542..42dfe94 100644 --- a/docs/python-api.rst +++ b/docs/python-api.rst @@ -6,6 +6,65 @@ .. contents:: :local: +.. _python_api_getting_started: + +Getting started +=============== + +Here's how to create a new SQLite database file containing a new ``chickens`` table, populated with four records: + +.. code-block:: python + + from sqlite_utils import Database + + db = Database("chickens.db") + db["chickens"].insert_all([{ + "name": "Azi", + "color": "blue", + }, { + "name": "Lila", + "color": "blue", + }, { + "name": "Suna", + "color": "gold", + }, { + "name": "Cardi", + "color": "black", + }]) + +You can loop through those rows like this: + +.. code-block:: python + + for row in db["chickens"].rows: + print(row) + +Which outputs the following:: + + {'name': 'Azi', 'color': 'blue'} + {'name': 'Lila', 'color': 'blue'} + {'name': 'Suna', 'color': 'gold'} + {'name': 'Cardi', 'color': 'black'} + +To run a SQL query, use :ref:`db.query() `: + +.. code-block:: python + + for row in db.query(""" + select color, count(*) + from chickens group by color + order by count(*) desc + """): + print(row) + +Which outputs:: + + {'color': 'blue', 'count(*)': 2} + {'color': 'gold', 'count(*)': 1} + {'color': 'black', 'count(*)': 1} + +.. _python_api_connect: + Connecting to or creating a database ====================================