diff --git a/README.md b/README.md index 3c47ccc..fe6f9bb 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ working across different projects via [VisualMode](https://www.visualmode.dev/). For a steady stream of TILs, [sign up for my newsletter](https://visualmode.kit.com/newsletter). -_1835 TILs and counting..._ +_1836 TILs and counting..._ See some of the other learning resources I work on: @@ -1068,6 +1068,7 @@ If you've learned something here, support my efforts writing daily TILs by - [Access Instance Variables](python/access-instance-variables.md) - [Access Most Recent Return Value In REPL](python/access-most-recent-return-value-in-repl.md) +- [Access SQLite Result Values By Name With Row Factory](python/access-sqlite-result-values-by-name-with-row-factory.md) - [Access Variables Outside Loop Scope](python/access-variables-outside-loop-scope.md) - [Argument Defaults Are Evaluated When Function Is Defined](python/argument-defaults-are-evaluated-when-function-is-defined.md) - [Assert Is Only A Development Check](python/assert-is-only-a-development-check.md) diff --git a/python/access-sqlite-result-values-by-name-with-row-factory.md b/python/access-sqlite-result-values-by-name-with-row-factory.md new file mode 100644 index 0000000..7ee6ffa --- /dev/null +++ b/python/access-sqlite-result-values-by-name-with-row-factory.md @@ -0,0 +1,35 @@ +# Access SQLite Result Values By Name With Row Factory + +The default shape of a result from executing a row-returning statement with +`sqlite3` is a tuple. Whose values can be accessed positionally. + +```python +>>> res = conn.execute("select * from projects;") +>>> res.fetchone() +(1, 'py-vmt', '2026-07-25 14:53:44', '2026-07-25 14:53:44') +``` + +If I want something a bit nicer, I can enable [_Row Factory_ +results](https://docs.python.org/3/library/sqlite3.html#how-to-create-and-use-row-factories) +for my connection. The values on a _row_ can be accessed by name as well as +positionally. + +```python +>>> conn.row_factory = sqlite3.Row +>>> res = conn.execute("select * from projects;") +>>> res.fetchone() + +>>> r1 = _ +>>> r1 + +>>> r1["name"] +'py-vmt' +>>> r1["id"] +1 +>>> r1[1] +'py-vmt' +``` + +[I used Row Factory on a project +recently](https://github.com/jbranchaud/py-vmt/pull/9/changes) and I think it +made for an improvement in the readability of the code.