Skip to content

Commit f0bf795

Browse files
author
Erlend Egeberg Aasland
authoredJul 29, 2022
gh-95273: Move sqlite3 executemany examples from reference to tutorial (#95351)
1 parent e9c8de6 commit f0bf795

File tree

3 files changed

+26
-54
lines changed

3 files changed

+26
-54
lines changed
 

‎Doc/includes/sqlite3/executemany_1.py

-26
This file was deleted.

‎Doc/includes/sqlite3/executemany_2.py

-17
This file was deleted.

‎Doc/library/sqlite3.rst

+26-11
Original file line numberDiff line numberDiff line change
@@ -67,15 +67,28 @@ after restarting the Python interpreter::
6767
con = sqlite3.connect('example.db')
6868
cur = con.cursor()
6969

70-
To retrieve data after executing a SELECT statement, either treat the cursor as
71-
an :term:`iterator`, call the cursor's :meth:`~Cursor.fetchone` method to
72-
retrieve a single matching row, or call :meth:`~Cursor.fetchall` to get a list
73-
of the matching rows.
70+
At this point, our database only contains one row::
7471

75-
This example uses the iterator form::
72+
>>> res = cur.execute('SELECT count(rowid) FROM stocks')
73+
>>> print(res.fetchone())
74+
(1,)
75+
76+
The result is a one-item :class:`tuple`:
77+
one row, with one column.
78+
Now, let us insert three more rows of data,
79+
using :meth:`~Cursor.executemany`::
80+
81+
>>> data = [
82+
('2006-03-28', 'BUY', 'IBM', 1000, 45.0),
83+
('2006-04-05', 'BUY', 'MSFT', 1000, 72.0),
84+
('2006-04-06', 'SELL', 'IBM', 500, 53.0),
85+
]
86+
>>> cur.executemany('INSERT INTO stocks VALUES(?, ?, ?, ?)', data)
87+
88+
Then, retrieve the data by iterating over the result of a ``SELECT`` statement::
7689

7790
>>> for row in cur.execute('SELECT * FROM stocks ORDER BY price'):
78-
print(row)
91+
... print(row)
7992

8093
('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
8194
('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
@@ -990,12 +1003,14 @@ Cursor Objects
9901003
:term:`iterator` yielding parameters instead of a sequence.
9911004
Uses the same implicit transaction handling as :meth:`~Cursor.execute`.
9921005

993-
.. literalinclude:: ../includes/sqlite3/executemany_1.py
994-
995-
Here's a shorter example using a :term:`generator`:
996-
997-
.. literalinclude:: ../includes/sqlite3/executemany_2.py
1006+
Example::
9981007

1008+
data = [
1009+
("row1",),
1010+
("row2",),
1011+
]
1012+
# cur is an sqlite3.Cursor object
1013+
cur.executemany("insert into t values(?)", data)
9991014

10001015
.. method:: executescript(sql_script, /)
10011016

0 commit comments

Comments
 (0)
Please sign in to comment.