Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
C
cpython
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
Analytics
Analytics
Repository
Value Stream
Wiki
Wiki
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Commits
Issue Boards
Open sidebar
Kirill Smelkov
cpython
Commits
26497d91
Commit
26497d91
authored
Oct 08, 2008
by
Georg Brandl
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
#4059: patch up some sqlite docs.
parent
0e21a797
Changes
1
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
134 additions
and
52 deletions
+134
-52
Doc/library/sqlite3.rst
Doc/library/sqlite3.rst
+134
-52
No files found.
Doc/library/sqlite3.rst
View file @
26497d91
...
@@ -27,7 +27,7 @@ represents the database. Here the data will be stored in the
...
@@ -27,7 +27,7 @@ represents the database. Here the data will be stored in the
You can also supply the special name ``:memory:`` to create a database in RAM.
You can also supply the special name ``:memory:`` to create a database in RAM.
Once you have a :class:`Connection`, you can create a :class:`Cursor` object
Once you have a :class:`Connection`, you can create a :class:`Cursor` object
and call its :meth:`execute` method to perform SQL commands::
and call its :meth:`
~Cursor.
execute` method to perform SQL commands::
c = conn.cursor()
c = conn.cursor()
...
@@ -52,7 +52,7 @@ is insecure; it makes your program vulnerable to an SQL injection attack.
...
@@ -52,7 +52,7 @@ is insecure; it makes your program vulnerable to an SQL injection attack.
Instead, use the DB-API's parameter substitution. Put ``?`` as a placeholder
Instead, use the DB-API's parameter substitution. Put ``?`` as a placeholder
wherever you want to use a value, and then provide a tuple of values as the
wherever you want to use a value, and then provide a tuple of values as the
second argument to the cursor's :meth:`execute` method. (Other database modules
second argument to the cursor's :meth:`
~Cursor.
execute` method. (Other database modules
may use a different placeholder, such as ``%s`` or ``:1``.) For example::
may use a different placeholder, such as ``%s`` or ``:1``.) For example::
# Never do this -- insecure!
# Never do this -- insecure!
...
@@ -71,8 +71,8 @@ may use a different placeholder, such as ``%s`` or ``:1``.) For example::
...
@@ -71,8 +71,8 @@ may use a different placeholder, such as ``%s`` or ``:1``.) For example::
c.execute('insert into stocks values (?,?,?,?,?)', t)
c.execute('insert into stocks values (?,?,?,?,?)', t)
To retrieve data after executing a SELECT statement, you can either treat the
To retrieve data after executing a SELECT statement, you can either treat the
cursor as an :term:`iterator`, call the cursor's :meth:`fetchone` method to
cursor as an :term:`iterator`, call the cursor's :meth:`
~Cursor.
fetchone` method to
retrieve a single matching row, or call :meth:`fetchall` to get a list of the
retrieve a single matching row, or call :meth:`
~Cursor.
fetchall` to get a list of the
matching rows.
matching rows.
This example uses the iterator form::
This example uses the iterator form::
...
@@ -130,7 +130,7 @@ Module functions and constants
...
@@ -130,7 +130,7 @@ Module functions and constants
returns. It will look for a string formed [mytype] in there, and then decide
returns. It will look for a string formed [mytype] in there, and then decide
that 'mytype' is the type of the column. It will try to find an entry of
that 'mytype' is the type of the column. It will try to find an entry of
'mytype' in the converters dictionary and then use the converter function found
'mytype' in the converters dictionary and then use the converter function found
there to return the value. The column name found in :attr:`
c
ursor.description`
there to return the value. The column name found in :attr:`
C
ursor.description`
is only the first word of the column name, i. e. if you use something like
is only the first word of the column name, i. e. if you use something like
``'as "x [datetime]"'`` in your SQL, then we will parse out everything until the
``'as "x [datetime]"'`` in your SQL, then we will parse out everything until the
first blank for the column name: the column name would simply be "x".
first blank for the column name: the column name would simply be "x".
...
@@ -217,11 +217,13 @@ Module functions and constants
...
@@ -217,11 +217,13 @@ Module functions and constants
Connection Objects
Connection Objects
------------------
------------------
A :class:`Connection` instance has the following attributes and methods:
.. class:: Connection
A SQLite database connection has the following attributes and methods:
.. attribute:: Connection.isolation_level
.. attribute:: Connection.isolation_level
Get or set the current isolation level.
None
for autocommit mode or one of
Get or set the current isolation level.
:const:`None`
for autocommit mode or one of
"DEFERRED", "IMMEDIATE" or "EXLUSIVE". See section
"DEFERRED", "IMMEDIATE" or "EXLUSIVE". See section
:ref:`sqlite3-controlling-transactions` for a more detailed explanation.
:ref:`sqlite3-controlling-transactions` for a more detailed explanation.
...
@@ -236,7 +238,7 @@ A :class:`Connection` instance has the following attributes and methods:
...
@@ -236,7 +238,7 @@ A :class:`Connection` instance has the following attributes and methods:
.. method:: Connection.commit()
.. method:: Connection.commit()
This method commits the current transaction. If you don't call this method,
This method commits the current transaction. If you don't call this method,
anything you did since the last call to
commit()
is not visible from from
anything you did since the last call to
``commit()``
is not visible from from
other database connections. If you wonder why you don't see the data you've
other database connections. If you wonder why you don't see the data you've
written to the database, please check you didn't forget to call this method.
written to the database, please check you didn't forget to call this method.
...
@@ -386,9 +388,9 @@ A :class:`Connection` instance has the following attributes and methods:
...
@@ -386,9 +388,9 @@ A :class:`Connection` instance has the following attributes and methods:
.. attribute:: Connection.text_factory
.. attribute:: Connection.text_factory
Using this attribute you can control what objects are returned for the
TEXT data
Using this attribute you can control what objects are returned for the
``TEXT``
type. By default, this attribute is set to :class:`unicode` and the
data
type. By default, this attribute is set to :class:`unicode` and the
:mod:`sqlite3` module will return Unicode objects for
TEXT
. If you want to
:mod:`sqlite3` module will return Unicode objects for
``TEXT``
. If you want to
return bytestrings instead, you can set it to :class:`str`.
return bytestrings instead, you can set it to :class:`str`.
For efficiency reasons, there's also a way to return Unicode objects only for
For efficiency reasons, there's also a way to return Unicode objects only for
...
@@ -435,8 +437,9 @@ A :class:`Connection` instance has the following attributes and methods:
...
@@ -435,8 +437,9 @@ A :class:`Connection` instance has the following attributes and methods:
Cursor Objects
Cursor Objects
--------------
--------------
A :class:`Cursor` instance has the following attributes and methods:
.. class:: Cursor
A SQLite database cursor has the following attributes and methods:
.. method:: Cursor.execute(sql, [parameters])
.. method:: Cursor.execute(sql, [parameters])
...
@@ -475,7 +478,7 @@ A :class:`Cursor` instance has the following attributes and methods:
...
@@ -475,7 +478,7 @@ A :class:`Cursor` instance has the following attributes and methods:
.. method:: Cursor.executescript(sql_script)
.. method:: Cursor.executescript(sql_script)
This is a nonstandard convenience method for executing multiple SQL statements
This is a nonstandard convenience method for executing multiple SQL statements
at once. It issues a
COMMIT
statement first, then executes the SQL script it
at once. It issues a
``COMMIT``
statement first, then executes the SQL script it
gets as a parameter.
gets as a parameter.
*sql_script* can be a bytestring or a Unicode string.
*sql_script* can be a bytestring or a Unicode string.
...
@@ -488,7 +491,7 @@ A :class:`Cursor` instance has the following attributes and methods:
...
@@ -488,7 +491,7 @@ A :class:`Cursor` instance has the following attributes and methods:
.. method:: Cursor.fetchone()
.. method:: Cursor.fetchone()
Fetches the next row of a query result set, returning a single sequence,
Fetches the next row of a query result set, returning a single sequence,
or
``None`
` when no more data is available.
or
:const:`None
` when no more data is available.
.. method:: Cursor.fetchmany([size=cursor.arraysize])
.. method:: Cursor.fetchmany([size=cursor.arraysize])
...
@@ -527,8 +530,8 @@ A :class:`Cursor` instance has the following attributes and methods:
...
@@ -527,8 +530,8 @@ A :class:`Cursor` instance has the following attributes and methods:
into :attr:`rowcount`.
into :attr:`rowcount`.
As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
case no
executeXX() has been performed on the cursor or the rowcount of the last
case no
``executeXX()`` has been performed on the cursor or the rowcount of the
operation is not determinable by the interface".
last
operation is not determinable by the interface".
This includes ``SELECT`` statements because we cannot determine the number of
This includes ``SELECT`` statements because we cannot determine the number of
rows a query produced until all rows were fetched.
rows a query produced until all rows were fetched.
...
@@ -540,6 +543,81 @@ A :class:`Cursor` instance has the following attributes and methods:
...
@@ -540,6 +543,81 @@ A :class:`Cursor` instance has the following attributes and methods:
method. For operations other than ``INSERT`` or when :meth:`executemany` is
method. For operations other than ``INSERT`` or when :meth:`executemany` is
called, :attr:`lastrowid` is set to :const:`None`.
called, :attr:`lastrowid` is set to :const:`None`.
.. attribute:: Cursor.description
This read-only attribute provides the column names of the last query. To
remain compatible with the Python DB API, it returns a 7-tuple for each
column where the last six items of each tuple are :const:`None`.
It is set for ``SELECT`` statements without any matching rows as well.
.. _sqlite3-row-objects:
Row Objects
-----------
.. class:: Row
A :class:`Row` instance serves as a highly optimized
:attr:`~Connection.row_factory` for :class:`Connection` objects.
It tries to mimic a tuple in most of its features.
It supports mapping access by column name and index, iteration,
representation, equality testing and :func:`len`.
If two :class:`Row` objects have exactly the same columns and their
members are equal, they compare equal.
.. versionchanged:: 2.6
Added iteration and equality (hashability).
.. method:: keys
This method returns a tuple of column names. Immediately after a query,
it is the first member of each tuple in :attr:`Cursor.description`.
.. versionadded:: 2.6
Let's assume we initialize a table as in the example given above::
conn = sqlite3.connect(":memory:")
c = conn.cursor()
c.execute('''create table stocks
(date text, trans text, symbol text,
qty real, price real)''')
c.execute("""insert into stocks
values ('2006-01-05','BUY','RHAT',100,35.14)""")
conn.commit()
c.close()
Now we plug :class:`Row` in::
>>> conn.row_factory = sqlite3.Row
>>> c = conn.cursor()
>>> c.execute('select * from stocks')
<sqlite3.Cursor object at 0x7f4e7dd8fa80>
>>> r = c.fetchone()
>>> type(r)
<type 'sqlite3.Row'>
>>> r
(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001)
>>> len(r)
5
>>> r[2]
u'RHAT'
>>> r.keys()
['date', 'trans', 'symbol', 'qty', 'price']
>>> r['qty']
100.0
>>> for member in r: print member
...
2006-01-05
BUY
RHAT
100.0
35.14
.. _sqlite3-types:
.. _sqlite3-types:
SQLite and Python types
SQLite and Python types
...
@@ -549,43 +627,46 @@ SQLite and Python types
...
@@ -549,43 +627,46 @@ SQLite and Python types
Introduction
Introduction
^^^^^^^^^^^^
^^^^^^^^^^^^
SQLite natively supports the following types: NULL, INTEGER, REAL, TEXT, BLOB.
SQLite natively supports the following types: ``NULL``, ``INTEGER``,
``REAL``, ``TEXT``, ``BLOB``.
The following Python types can thus be sent to SQLite without any problem:
The following Python types can thus be sent to SQLite without any problem:
+------------------------+-------------+
+------------------------
-----
+-------------+
| Python type | SQLite type |
| Python type | SQLite type |
+========================+=============+
+========================
=====
+=============+
|
``None`` | NULL
|
|
:const:`None` | ``NULL``
|
+------------------------+-------------+
+------------------------
-----
+-------------+
|
``int`` | INTEGER
|
|
:class:`int` | ``INTEGER``
|
+------------------------+-------------+
+------------------------
-----
+-------------+
|
``long`` | INTEGER
|
|
:class:`long` | ``INTEGER``
|
+------------------------+-------------+
+------------------------
-----
+-------------+
|
``float`` | REAL
|
|
:class:`float` | ``REAL``
|
+------------------------+-------------+
+------------------------
-----
+-------------+
|
``str (UTF8-encoded)`` | TEXT
|
|
:class:`str` (UTF8-encoded) | ``TEXT``
|
+------------------------+-------------+
+------------------------
-----
+-------------+
|
``unicode`` | TEXT
|
|
:class:`unicode` | ``TEXT``
|
+------------------------+-------------+
+------------------------
-----
+-------------+
|
``buffer`` | BLOB
|
|
:class:`buffer` | ``BLOB``
|
+------------------------+-------------+
+------------------------
-----
+-------------+
This is how SQLite types are converted to Python types by default:
This is how SQLite types are converted to Python types by default:
+-------------+---------------------------------------------+
+-------------+---------------------------------------------
-
+
| SQLite type | Python type |
| SQLite type | Python type |
+=============+=============================================+
+=============+==============================================+
| ``NULL`` | None |
| ``NULL`` | :const:`None` |
+-------------+---------------------------------------------+
+-------------+----------------------------------------------+
| ``INTEGER`` | int or long, depending on size |
| ``INTEGER`` | :class:`int` or :class:`long`, |
+-------------+---------------------------------------------+
| | depending on size |
| ``REAL`` | float |
+-------------+----------------------------------------------+
+-------------+---------------------------------------------+
| ``REAL`` | :class:`float` |
| ``TEXT`` | depends on text_factory, unicode by default |
+-------------+----------------------------------------------+
+-------------+---------------------------------------------+
| ``TEXT`` | depends on :attr:`~Connection.text_factory`, |
| ``BLOB`` | buffer |
| | :class:`unicode` by default |
+-------------+---------------------------------------------+
+-------------+----------------------------------------------+
| ``BLOB`` | :class:`buffer` |
+-------------+----------------------------------------------+
The type system of the :mod:`sqlite3` module is extensible in two ways: you can
The type system of the :mod:`sqlite3` module is extensible in two ways: you can
store additional Python types in a SQLite database via object adaptation, and
store additional Python types in a SQLite database via object adaptation, and
...
@@ -713,9 +794,10 @@ Controlling Transactions
...
@@ -713,9 +794,10 @@ Controlling Transactions
------------------------
------------------------
By default, the :mod:`sqlite3` module opens transactions implicitly before a
By default, the :mod:`sqlite3` module opens transactions implicitly before a
Data Modification Language (DML) statement (i.e. INSERT/UPDATE/DELETE/REPLACE),
Data Modification Language (DML) statement (i.e.
and commits transactions implicitly before a non-DML, non-query statement (i. e.
``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions
anything other than SELECT/INSERT/UPDATE/DELETE/REPLACE).
implicitly before a non-DML, non-query statement (i. e.
anything other than ``SELECT`` or the aforementioned).
So if you are within a transaction and issue a command like ``CREATE TABLE
So if you are within a transaction and issue a command like ``CREATE TABLE
...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
...
@@ -724,7 +806,7 @@ is that some of these commands don't work within transactions. The other reason
...
@@ -724,7 +806,7 @@ is that some of these commands don't work within transactions. The other reason
is that pysqlite needs to keep track of the transaction state (if a transaction
is that pysqlite needs to keep track of the transaction state (if a transaction
is active or not).
is active or not).
You can control which kind of
"BEGIN"
statements pysqlite implicitly executes
You can control which kind of
``BEGIN``
statements pysqlite implicitly executes
(or none at all) via the *isolation_level* parameter to the :func:`connect`
(or none at all) via the *isolation_level* parameter to the :func:`connect`
call, or via the :attr:`isolation_level` property of connections.
call, or via the :attr:`isolation_level` property of connections.
...
@@ -748,7 +830,7 @@ Using the nonstandard :meth:`execute`, :meth:`executemany` and
...
@@ -748,7 +830,7 @@ Using the nonstandard :meth:`execute`, :meth:`executemany` and
be written more concisely because you don't have to create the (often
be written more concisely because you don't have to create the (often
superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
objects are created implicitly and these shortcut methods return the cursor
objects are created implicitly and these shortcut methods return the cursor
objects. This way, you can execute a
SELECT
statement and iterate over it
objects. This way, you can execute a
``SELECT``
statement and iterate over it
directly using only a single call on the :class:`Connection` object.
directly using only a single call on the :class:`Connection` object.
.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
.. literalinclude:: ../includes/sqlite3/shortcut_methods.py
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment