Changeset 391 for python/trunk/Doc/library/sqlite3.rst
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Doc/library/sqlite3.rst
r2 r391 4 4 .. module:: sqlite3 5 5 :synopsis: A DB-API 2.0 implementation using SQLite 3.x. 6 .. sectionauthor:: Gerhard Hà €ring <gh@ghaering.de>6 .. sectionauthor:: Gerhard HÀring <gh@ghaering.de> 7 7 8 8 … … 16 16 PostgreSQL or Oracle. 17 17 18 sqlite3 was written by Gerhard HÀring and provides a SQL interface compliant 19 with the DB-API 2.0 specification described by :pep:`249`.18 The sqlite3 module was written by Gerhard HÀring. It provides a SQL interface 19 compliant with the DB-API 2.0 specification described by :pep:`249`. 20 20 21 21 To use the module, you must first create a :class:`Connection` object that 22 22 represents the database. Here the data will be stored in the 23 :file:`/tmp/example` file:: 24 25 conn = sqlite3.connect('/tmp/example') 23 :file:`example.db` file:: 24 25 import sqlite3 26 conn = sqlite3.connect('example.db') 26 27 27 28 You can also supply the special name ``:memory:`` to create a database in RAM. … … 33 34 34 35 # Create table 35 c.execute('''create table stocks 36 (date text, trans text, symbol text, 37 qty real, price real)''') 36 c.execute('''CREATE TABLE stocks 37 (date text, trans text, symbol text, qty real, price real)''') 38 38 39 39 # Insert a row of data 40 c.execute("""insert into stocks 41 values ('2006-01-05','BUY','RHAT',100,35.14)""") 40 c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)") 42 41 43 42 # Save (commit) the changes 44 43 conn.commit() 45 44 46 # We can also close the cursor if we are done with it 47 c.close() 45 # We can also close the connection if we are done with it. 46 # Just be sure any changes have been committed or they will be lost. 47 conn.close() 48 49 The data you've saved is persistent and is available in subsequent sessions:: 50 51 import sqlite3 52 conn = sqlite3.connect('example.db') 53 c = conn.cursor() 48 54 49 55 Usually your SQL operations will need to use values from Python variables. You 50 56 shouldn't assemble your query using Python's string operations because doing so 51 is insecure; it makes your program vulnerable to an SQL injection attack. 57 is insecure; it makes your program vulnerable to an SQL injection attack 58 (see http://xkcd.com/327/ for humorous example of what can go wrong). 52 59 53 60 Instead, use the DB-API's parameter substitution. Put ``?`` as a placeholder … … 58 65 59 66 # Never do this -- insecure! 60 symbol = ' IBM'61 c.execute(" ... wheresymbol = '%s'" % symbol)67 symbol = 'RHAT' 68 c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol) 62 69 63 70 # Do this instead 64 t = (symbol,) 65 c.execute('select * from stocks where symbol=?', t) 66 67 # Larger example 68 for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), 69 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00), 70 ('2006-04-06', 'SELL', 'IBM', 500, 53.00), 71 ]: 72 c.execute('insert into stocks values (?,?,?,?,?)', t) 71 t = ('RHAT',) 72 c.execute('SELECT * FROM stocks WHERE symbol=?', t) 73 print c.fetchone() 74 75 # Larger example that inserts many records at a time 76 purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), 77 ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00), 78 ('2006-04-06', 'SELL', 'IBM', 500, 53.00), 79 ] 80 c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases) 73 81 74 82 To retrieve data after executing a SELECT statement, you can either treat the … … 79 87 This example uses the iterator form:: 80 88 81 >>> c = conn.cursor() 82 >>> c.execute('select * from stocks order by price') 83 >>> for row in c: 84 ... print row 85 ... 86 (u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001) 89 >>> for row in c.execute('SELECT * FROM stocks ORDER BY price'): 90 print row 91 92 (u'2006-01-05', u'BUY', u'RHAT', 100, 35.14) 87 93 (u'2006-03-28', u'BUY', u'IBM', 1000, 45.0) 88 94 (u'2006-04-06', u'SELL', u'IBM', 500, 53.0) 89 (u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0) 90 >>> 95 (u'2006-04-05', u'BUY', u'MSFT', 1000, 72.0) 91 96 92 97 93 98 .. seealso:: 94 99 95 http:// www.pysqlite.org100 http://code.google.com/p/pysqlite/ 96 101 The pysqlite web page -- sqlite3 is developed externally under the name 97 102 "pysqlite". … … 101 106 available data types for the supported SQL dialect. 102 107 108 http://www.w3schools.com/sql/ 109 Tutorial, reference and examples for learning SQL syntax. 110 103 111 :pep:`249` - Database API Specification 2.0 104 112 PEP written by Marc-André Lemburg. … … 110 118 ------------------------------ 111 119 120 121 .. data:: version 122 123 The version number of this module, as a string. This is not the version of 124 the SQLite library. 125 126 .. data:: version_info 127 128 The version number of this module, as a tuple of integers. This is not the 129 version of the SQLite library. 130 131 .. data:: sqlite_version 132 133 The version number of the run-time SQLite library, as a string. 134 135 .. data:: sqlite_version_info 136 137 The version number of the run-time SQLite library, as a tuple of integers. 112 138 113 139 .. data:: PARSE_DECLTYPES … … 139 165 140 166 141 .. function:: connect(database[, timeout, isolation_level, detect_types, factory])167 .. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements]) 142 168 143 169 Opens a connection to the SQLite database file *database*. You can use … … 154 180 :attr:`Connection.isolation_level` property of :class:`Connection` objects. 155 181 156 SQLite natively supports only the types TEXT, INTEGER, FLOAT, BLOB and NULL. If182 SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If 157 183 you want to use other types you must add support for them yourself. The 158 184 *detect_types* parameter and the using custom **converters** registered with the … … 224 250 A SQLite database connection has the following attributes and methods: 225 251 226 .. attribute:: Connection.isolation_level 227 228 Get or set the current isolation level. :const:`None` for autocommit mode or 229 one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section 230 :ref:`sqlite3-controlling-transactions` for a more detailed explanation. 231 232 233 .. method:: Connection.cursor([cursorClass]) 234 235 The cursor method accepts a single optional parameter *cursorClass*. If 236 supplied, this must be a custom cursor class that extends 237 :class:`sqlite3.Cursor`. 238 239 240 .. method:: Connection.commit() 241 242 This method commits the current transaction. If you don't call this method, 243 anything you did since the last call to ``commit()`` is not visible from from 244 other database connections. If you wonder why you don't see the data you've 245 written to the database, please check you didn't forget to call this method. 246 247 .. method:: Connection.rollback() 248 249 This method rolls back any changes to the database since the last call to 250 :meth:`commit`. 251 252 .. method:: Connection.close() 253 254 This closes the database connection. Note that this does not automatically 255 call :meth:`commit`. If you just close your database connection without 256 calling :meth:`commit` first, your changes will be lost! 257 258 .. method:: Connection.execute(sql, [parameters]) 259 260 This is a nonstandard shortcut that creates an intermediate cursor object by 261 calling the cursor method, then calls the cursor's 262 :meth:`execute<Cursor.execute>` method with the parameters given. 263 264 265 .. method:: Connection.executemany(sql, [parameters]) 266 267 This is a nonstandard shortcut that creates an intermediate cursor object by 268 calling the cursor method, then calls the cursor's 269 :meth:`executemany<Cursor.executemany>` method with the parameters given. 270 271 .. method:: Connection.executescript(sql_script) 272 273 This is a nonstandard shortcut that creates an intermediate cursor object by 274 calling the cursor method, then calls the cursor's 275 :meth:`executescript<Cursor.executescript>` method with the parameters 276 given. 277 278 279 .. method:: Connection.create_function(name, num_params, func) 280 281 Creates a user-defined function that you can later use from within SQL 282 statements under the function name *name*. *num_params* is the number of 283 parameters the function accepts, and *func* is a Python callable that is called 284 as the SQL function. 285 286 The function can return any of the types supported by SQLite: unicode, str, int, 287 long, float, buffer and None. 288 289 Example: 290 291 .. literalinclude:: ../includes/sqlite3/md5func.py 292 293 294 .. method:: Connection.create_aggregate(name, num_params, aggregate_class) 295 296 Creates a user-defined aggregate function. 297 298 The aggregate class must implement a ``step`` method, which accepts the number 299 of parameters *num_params*, and a ``finalize`` method which will return the 300 final result of the aggregate. 301 302 The ``finalize`` method can return any of the types supported by SQLite: 303 unicode, str, int, long, float, buffer and None. 304 305 Example: 306 307 .. literalinclude:: ../includes/sqlite3/mysumaggr.py 308 309 310 .. method:: Connection.create_collation(name, callable) 311 312 Creates a collation with the specified *name* and *callable*. The callable will 313 be passed two string arguments. It should return -1 if the first is ordered 314 lower than the second, 0 if they are ordered equal and 1 if the first is ordered 315 higher than the second. Note that this controls sorting (ORDER BY in SQL) so 316 your comparisons don't affect other SQL operations. 317 318 Note that the callable will get its parameters as Python bytestrings, which will 319 normally be encoded in UTF-8. 320 321 The following example shows a custom collation that sorts "the wrong way": 322 323 .. literalinclude:: ../includes/sqlite3/collation_reverse.py 324 325 To remove a collation, call ``create_collation`` with None as callable:: 326 327 con.create_collation("reverse", None) 328 329 330 .. method:: Connection.interrupt() 331 332 You can call this method from a different thread to abort any queries that might 333 be executing on the connection. The query will then abort and the caller will 334 get an exception. 335 336 337 .. method:: Connection.set_authorizer(authorizer_callback) 338 339 This routine registers a callback. The callback is invoked for each attempt to 340 access a column of a table in the database. The callback should return 341 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL 342 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the 343 column should be treated as a NULL value. These constants are available in the 344 :mod:`sqlite3` module. 345 346 The first argument to the callback signifies what kind of operation is to be 347 authorized. The second and third argument will be arguments or :const:`None` 348 depending on the first argument. The 4th argument is the name of the database 349 ("main", "temp", etc.) if applicable. The 5th argument is the name of the 350 inner-most trigger or view that is responsible for the access attempt or 351 :const:`None` if this access attempt is directly from input SQL code. 352 353 Please consult the SQLite documentation about the possible values for the first 354 argument and the meaning of the second and third argument depending on the first 355 one. All necessary constants are available in the :mod:`sqlite3` module. 356 357 358 .. method:: Connection.set_progress_handler(handler, n) 359 360 .. versionadded:: 2.6 361 362 This routine registers a callback. The callback is invoked for every *n* 363 instructions of the SQLite virtual machine. This is useful if you want to 364 get called from SQLite during long-running operations, for example to update 365 a GUI. 366 367 If you want to clear any previously installed progress handler, call the 368 method with :const:`None` for *handler*. 369 370 371 .. attribute:: Connection.row_factory 372 373 You can change this attribute to a callable that accepts the cursor and the 374 original row as a tuple and will return the real result row. This way, you can 375 implement more advanced ways of returning results, such as returning an object 376 that can also access columns by name. 377 378 Example: 379 380 .. literalinclude:: ../includes/sqlite3/row_factory.py 381 382 If returning a tuple doesn't suffice and you want name-based access to 383 columns, you should consider setting :attr:`row_factory` to the 384 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both 385 index-based and case-insensitive name-based access to columns with almost no 386 memory overhead. It will probably be better than your own custom 387 dictionary-based approach or even a db_row based solution. 388 389 .. XXX what's a db_row-based solution? 390 391 392 .. attribute:: Connection.text_factory 393 394 Using this attribute you can control what objects are returned for the ``TEXT`` 395 data type. By default, this attribute is set to :class:`unicode` and the 396 :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to 397 return bytestrings instead, you can set it to :class:`str`. 398 399 For efficiency reasons, there's also a way to return Unicode objects only for 400 non-ASCII data, and bytestrings otherwise. To activate it, set this attribute to 401 :const:`sqlite3.OptimizedUnicode`. 402 403 You can also set it to any other callable that accepts a single bytestring 404 parameter and returns the resulting object. 405 406 See the following example code for illustration: 407 408 .. literalinclude:: ../includes/sqlite3/text_factory.py 409 410 411 .. attribute:: Connection.total_changes 412 413 Returns the total number of database rows that have been modified, inserted, or 414 deleted since the database connection was opened. 415 416 417 .. attribute:: Connection.iterdump 418 419 Returns an iterator to dump the database in an SQL text format. Useful when 420 saving an in-memory database for later restoration. This function provides 421 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3` 422 shell. 423 424 .. versionadded:: 2.6 425 426 Example:: 427 428 # Convert file existing_db.db to SQL dump file dump.sql 429 import sqlite3, os 430 431 con = sqlite3.connect('existing_db.db') 432 with open('dump.sql', 'w') as f: 433 for line in con.iterdump(): 434 f.write('%s\n' % line) 252 .. attribute:: isolation_level 253 254 Get or set the current isolation level. :const:`None` for autocommit mode or 255 one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section 256 :ref:`sqlite3-controlling-transactions` for a more detailed explanation. 257 258 259 .. method:: cursor([cursorClass]) 260 261 The cursor method accepts a single optional parameter *cursorClass*. If 262 supplied, this must be a custom cursor class that extends 263 :class:`sqlite3.Cursor`. 264 265 .. method:: commit() 266 267 This method commits the current transaction. If you don't call this method, 268 anything you did since the last call to ``commit()`` is not visible from 269 other database connections. If you wonder why you don't see the data you've 270 written to the database, please check you didn't forget to call this method. 271 272 .. method:: rollback() 273 274 This method rolls back any changes to the database since the last call to 275 :meth:`commit`. 276 277 .. method:: close() 278 279 This closes the database connection. Note that this does not automatically 280 call :meth:`commit`. If you just close your database connection without 281 calling :meth:`commit` first, your changes will be lost! 282 283 .. method:: execute(sql, [parameters]) 284 285 This is a nonstandard shortcut that creates an intermediate cursor object by 286 calling the cursor method, then calls the cursor's :meth:`execute 287 <Cursor.execute>` method with the parameters given. 288 289 290 .. method:: executemany(sql, [parameters]) 291 292 This is a nonstandard shortcut that creates an intermediate cursor object by 293 calling the cursor method, then calls the cursor's :meth:`executemany 294 <Cursor.executemany>` method with the parameters given. 295 296 .. method:: executescript(sql_script) 297 298 This is a nonstandard shortcut that creates an intermediate cursor object by 299 calling the cursor method, then calls the cursor's :meth:`executescript 300 <Cursor.executescript>` method with the parameters given. 301 302 303 .. method:: create_function(name, num_params, func) 304 305 Creates a user-defined function that you can later use from within SQL 306 statements under the function name *name*. *num_params* is the number of 307 parameters the function accepts, and *func* is a Python callable that is called 308 as the SQL function. 309 310 The function can return any of the types supported by SQLite: unicode, str, int, 311 long, float, buffer and None. 312 313 Example: 314 315 .. literalinclude:: ../includes/sqlite3/md5func.py 316 317 318 .. method:: create_aggregate(name, num_params, aggregate_class) 319 320 Creates a user-defined aggregate function. 321 322 The aggregate class must implement a ``step`` method, which accepts the number 323 of parameters *num_params*, and a ``finalize`` method which will return the 324 final result of the aggregate. 325 326 The ``finalize`` method can return any of the types supported by SQLite: 327 unicode, str, int, long, float, buffer and None. 328 329 Example: 330 331 .. literalinclude:: ../includes/sqlite3/mysumaggr.py 332 333 334 .. method:: create_collation(name, callable) 335 336 Creates a collation with the specified *name* and *callable*. The callable will 337 be passed two string arguments. It should return -1 if the first is ordered 338 lower than the second, 0 if they are ordered equal and 1 if the first is ordered 339 higher than the second. Note that this controls sorting (ORDER BY in SQL) so 340 your comparisons don't affect other SQL operations. 341 342 Note that the callable will get its parameters as Python bytestrings, which will 343 normally be encoded in UTF-8. 344 345 The following example shows a custom collation that sorts "the wrong way": 346 347 .. literalinclude:: ../includes/sqlite3/collation_reverse.py 348 349 To remove a collation, call ``create_collation`` with None as callable:: 350 351 con.create_collation("reverse", None) 352 353 354 .. method:: interrupt() 355 356 You can call this method from a different thread to abort any queries that might 357 be executing on the connection. The query will then abort and the caller will 358 get an exception. 359 360 361 .. method:: set_authorizer(authorizer_callback) 362 363 This routine registers a callback. The callback is invoked for each attempt to 364 access a column of a table in the database. The callback should return 365 :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL 366 statement should be aborted with an error and :const:`SQLITE_IGNORE` if the 367 column should be treated as a NULL value. These constants are available in the 368 :mod:`sqlite3` module. 369 370 The first argument to the callback signifies what kind of operation is to be 371 authorized. The second and third argument will be arguments or :const:`None` 372 depending on the first argument. The 4th argument is the name of the database 373 ("main", "temp", etc.) if applicable. The 5th argument is the name of the 374 inner-most trigger or view that is responsible for the access attempt or 375 :const:`None` if this access attempt is directly from input SQL code. 376 377 Please consult the SQLite documentation about the possible values for the first 378 argument and the meaning of the second and third argument depending on the first 379 one. All necessary constants are available in the :mod:`sqlite3` module. 380 381 382 .. method:: set_progress_handler(handler, n) 383 384 This routine registers a callback. The callback is invoked for every *n* 385 instructions of the SQLite virtual machine. This is useful if you want to 386 get called from SQLite during long-running operations, for example to update 387 a GUI. 388 389 If you want to clear any previously installed progress handler, call the 390 method with :const:`None` for *handler*. 391 392 .. versionadded:: 2.6 393 394 395 .. method:: enable_load_extension(enabled) 396 397 This routine allows/disallows the SQLite engine to load SQLite extensions 398 from shared libraries. SQLite extensions can define new functions, 399 aggregates or whole new virtual table implementations. One well-known 400 extension is the fulltext-search extension distributed with SQLite. 401 402 Loadable extensions are disabled by default. See [#f1]_. 403 404 .. versionadded:: 2.7 405 406 .. literalinclude:: ../includes/sqlite3/load_extension.py 407 408 .. method:: load_extension(path) 409 410 This routine loads a SQLite extension from a shared library. You have to 411 enable extension loading with :meth:`enable_load_extension` before you can 412 use this routine. 413 414 Loadable extensions are disabled by default. See [#f1]_. 415 416 .. versionadded:: 2.7 417 418 .. attribute:: row_factory 419 420 You can change this attribute to a callable that accepts the cursor and the 421 original row as a tuple and will return the real result row. This way, you can 422 implement more advanced ways of returning results, such as returning an object 423 that can also access columns by name. 424 425 Example: 426 427 .. literalinclude:: ../includes/sqlite3/row_factory.py 428 429 If returning a tuple doesn't suffice and you want name-based access to 430 columns, you should consider setting :attr:`row_factory` to the 431 highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both 432 index-based and case-insensitive name-based access to columns with almost no 433 memory overhead. It will probably be better than your own custom 434 dictionary-based approach or even a db_row based solution. 435 436 .. XXX what's a db_row-based solution? 437 438 439 .. attribute:: text_factory 440 441 Using this attribute you can control what objects are returned for the ``TEXT`` 442 data type. By default, this attribute is set to :class:`unicode` and the 443 :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to 444 return bytestrings instead, you can set it to :class:`str`. 445 446 For efficiency reasons, there's also a way to return Unicode objects only for 447 non-ASCII data, and bytestrings otherwise. To activate it, set this attribute to 448 :const:`sqlite3.OptimizedUnicode`. 449 450 You can also set it to any other callable that accepts a single bytestring 451 parameter and returns the resulting object. 452 453 See the following example code for illustration: 454 455 .. literalinclude:: ../includes/sqlite3/text_factory.py 456 457 458 .. attribute:: total_changes 459 460 Returns the total number of database rows that have been modified, inserted, or 461 deleted since the database connection was opened. 462 463 464 .. attribute:: iterdump 465 466 Returns an iterator to dump the database in an SQL text format. Useful when 467 saving an in-memory database for later restoration. This function provides 468 the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3` 469 shell. 470 471 .. versionadded:: 2.6 472 473 Example:: 474 475 # Convert file existing_db.db to SQL dump file dump.sql 476 import sqlite3, os 477 478 con = sqlite3.connect('existing_db.db') 479 with open('dump.sql', 'w') as f: 480 for line in con.iterdump(): 481 f.write('%s\n' % line) 435 482 436 483 … … 442 489 .. class:: Cursor 443 490 444 A SQLite database cursor has the following attributes and methods: 445 446 .. method:: Cursor.execute(sql, [parameters]) 447 448 Executes an SQL statement. The SQL statement may be parametrized (i. e. 449 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two 450 kinds of placeholders: question marks (qmark style) and named placeholders 451 (named style). 452 453 This example shows how to use parameters with qmark style: 454 455 .. literalinclude:: ../includes/sqlite3/execute_1.py 456 457 This example shows how to use the named style: 458 459 .. literalinclude:: ../includes/sqlite3/execute_2.py 460 461 :meth:`execute` will only execute a single SQL statement. If you try to execute 462 more than one statement with it, it will raise a Warning. Use 463 :meth:`executescript` if you want to execute multiple SQL statements with one 464 call. 465 466 467 .. method:: Cursor.executemany(sql, seq_of_parameters) 468 469 Executes an SQL command against all parameter sequences or mappings found in 470 the sequence *sql*. The :mod:`sqlite3` module also allows using an 471 :term:`iterator` yielding parameters instead of a sequence. 472 473 .. literalinclude:: ../includes/sqlite3/executemany_1.py 474 475 Here's a shorter example using a :term:`generator`: 476 477 .. literalinclude:: ../includes/sqlite3/executemany_2.py 478 479 480 .. method:: Cursor.executescript(sql_script) 481 482 This is a nonstandard convenience method for executing multiple SQL statements 483 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it 484 gets as a parameter. 485 486 *sql_script* can be a bytestring or a Unicode string. 487 488 Example: 489 490 .. literalinclude:: ../includes/sqlite3/executescript.py 491 492 493 .. method:: Cursor.fetchone() 494 495 Fetches the next row of a query result set, returning a single sequence, 496 or :const:`None` when no more data is available. 497 498 499 .. method:: Cursor.fetchmany([size=cursor.arraysize]) 500 501 Fetches the next set of rows of a query result, returning a list. An empty 502 list is returned when no more rows are available. 503 504 The number of rows to fetch per call is specified by the *size* parameter. 505 If it is not given, the cursor's arraysize determines the number of rows 506 to be fetched. The method should try to fetch as many rows as indicated by 507 the size parameter. If this is not possible due to the specified number of 508 rows not being available, fewer rows may be returned. 509 510 Note there are performance considerations involved with the *size* parameter. 511 For optimal performance, it is usually best to use the arraysize attribute. 512 If the *size* parameter is used, then it is best for it to retain the same 513 value from one :meth:`fetchmany` call to the next. 514 515 .. method:: Cursor.fetchall() 516 517 Fetches all (remaining) rows of a query result, returning a list. Note that 518 the cursor's arraysize attribute can affect the performance of this operation. 519 An empty list is returned when no rows are available. 520 521 522 .. attribute:: Cursor.rowcount 523 524 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this 525 attribute, the database engine's own support for the determination of "rows 526 affected"/"rows selected" is quirky. 527 528 For ``DELETE`` statements, SQLite reports :attr:`rowcount` as 0 if you make a 529 ``DELETE FROM table`` without any condition. 530 531 For :meth:`executemany` statements, the number of modifications are summed up 532 into :attr:`rowcount`. 533 534 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in 535 case no ``executeXX()`` has been performed on the cursor or the rowcount of the 536 last operation is not determinable by the interface". 537 538 This includes ``SELECT`` statements because we cannot determine the number of 539 rows a query produced until all rows were fetched. 540 541 .. attribute:: Cursor.lastrowid 542 543 This read-only attribute provides the rowid of the last modified row. It is 544 only set if you issued a ``INSERT`` statement using the :meth:`execute` 545 method. For operations other than ``INSERT`` or when :meth:`executemany` is 546 called, :attr:`lastrowid` is set to :const:`None`. 547 548 .. attribute:: Cursor.description 549 550 This read-only attribute provides the column names of the last query. To 551 remain compatible with the Python DB API, it returns a 7-tuple for each 552 column where the last six items of each tuple are :const:`None`. 553 554 It is set for ``SELECT`` statements without any matching rows as well. 491 A :class:`Cursor` instance has the following attributes and methods. 492 493 .. method:: execute(sql, [parameters]) 494 495 Executes an SQL statement. The SQL statement may be parameterized (i. e. 496 placeholders instead of SQL literals). The :mod:`sqlite3` module supports two 497 kinds of placeholders: question marks (qmark style) and named placeholders 498 (named style). 499 500 Here's an example of both styles: 501 502 .. literalinclude:: ../includes/sqlite3/execute_1.py 503 504 :meth:`execute` will only execute a single SQL statement. If you try to execute 505 more than one statement with it, it will raise a Warning. Use 506 :meth:`executescript` if you want to execute multiple SQL statements with one 507 call. 508 509 510 .. method:: executemany(sql, seq_of_parameters) 511 512 Executes an SQL command against all parameter sequences or mappings found in 513 the sequence *sql*. The :mod:`sqlite3` module also allows using an 514 :term:`iterator` yielding parameters instead of a sequence. 515 516 .. literalinclude:: ../includes/sqlite3/executemany_1.py 517 518 Here's a shorter example using a :term:`generator`: 519 520 .. literalinclude:: ../includes/sqlite3/executemany_2.py 521 522 523 .. method:: executescript(sql_script) 524 525 This is a nonstandard convenience method for executing multiple SQL statements 526 at once. It issues a ``COMMIT`` statement first, then executes the SQL script it 527 gets as a parameter. 528 529 *sql_script* can be a bytestring or a Unicode string. 530 531 Example: 532 533 .. literalinclude:: ../includes/sqlite3/executescript.py 534 535 536 .. method:: fetchone() 537 538 Fetches the next row of a query result set, returning a single sequence, 539 or :const:`None` when no more data is available. 540 541 542 .. method:: fetchmany([size=cursor.arraysize]) 543 544 Fetches the next set of rows of a query result, returning a list. An empty 545 list is returned when no more rows are available. 546 547 The number of rows to fetch per call is specified by the *size* parameter. 548 If it is not given, the cursor's arraysize determines the number of rows 549 to be fetched. The method should try to fetch as many rows as indicated by 550 the size parameter. If this is not possible due to the specified number of 551 rows not being available, fewer rows may be returned. 552 553 Note there are performance considerations involved with the *size* parameter. 554 For optimal performance, it is usually best to use the arraysize attribute. 555 If the *size* parameter is used, then it is best for it to retain the same 556 value from one :meth:`fetchmany` call to the next. 557 558 .. method:: fetchall() 559 560 Fetches all (remaining) rows of a query result, returning a list. Note that 561 the cursor's arraysize attribute can affect the performance of this operation. 562 An empty list is returned when no rows are available. 563 564 565 .. attribute:: rowcount 566 567 Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this 568 attribute, the database engine's own support for the determination of "rows 569 affected"/"rows selected" is quirky. 570 571 For :meth:`executemany` statements, the number of modifications are summed up 572 into :attr:`rowcount`. 573 574 As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in 575 case no ``executeXX()`` has been performed on the cursor or the rowcount of the 576 last operation is not determinable by the interface". This includes ``SELECT`` 577 statements because we cannot determine the number of rows a query produced 578 until all rows were fetched. 579 580 With SQLite versions before 3.6.5, :attr:`rowcount` is set to 0 if 581 you make a ``DELETE FROM table`` without any condition. 582 583 .. attribute:: lastrowid 584 585 This read-only attribute provides the rowid of the last modified row. It is 586 only set if you issued a ``INSERT`` statement using the :meth:`execute` 587 method. For operations other than ``INSERT`` or when :meth:`executemany` is 588 called, :attr:`lastrowid` is set to :const:`None`. 589 590 .. attribute:: description 591 592 This read-only attribute provides the column names of the last query. To 593 remain compatible with the Python DB API, it returns a 7-tuple for each 594 column where the last six items of each tuple are :const:`None`. 595 596 It is set for ``SELECT`` statements without any matching rows as well. 555 597 556 598 .. _sqlite3-row-objects: … … 583 625 Let's assume we initialize a table as in the example given above:: 584 626 585 586 587 588 589 590 591 592 593 627 conn = sqlite3.connect(":memory:") 628 c = conn.cursor() 629 c.execute('''create table stocks 630 (date text, trans text, symbol text, 631 qty real, price real)''') 632 c.execute("""insert into stocks 633 values ('2006-01-05','BUY','RHAT',100,35.14)""") 634 conn.commit() 635 c.close() 594 636 595 637 Now we plug :class:`Row` in:: 596 638 597 >>> conn.row_factory = sqlite3.Row 598 >>> c = conn.cursor() 599 >>> c.execute('select * from stocks') 600 <sqlite3.Cursor object at 0x7f4e7dd8fa80> 601 >>> r = c.fetchone() 602 >>> type(r) 603 <type 'sqlite3.Row'> 604 >>> r 605 (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001) 606 >>> len(r) 607 5 608 >>> r[2] 609 u'RHAT' 610 >>> r.keys() 611 ['date', 'trans', 'symbol', 'qty', 'price'] 612 >>> r['qty'] 613 100.0 614 >>> for member in r: print member 615 ... 616 2006-01-05 617 BUY 618 RHAT 619 100.0 620 35.14 639 >>> conn.row_factory = sqlite3.Row 640 >>> c = conn.cursor() 641 >>> c.execute('select * from stocks') 642 <sqlite3.Cursor object at 0x7f4e7dd8fa80> 643 >>> r = c.fetchone() 644 >>> type(r) 645 <type 'sqlite3.Row'> 646 >>> r 647 (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.14) 648 >>> len(r) 649 5 650 >>> r[2] 651 u'RHAT' 652 >>> r.keys() 653 ['date', 'trans', 'symbol', 'qty', 'price'] 654 >>> r['qty'] 655 100.0 656 >>> for member in r: 657 ... print member 658 ... 659 2006-01-05 660 BUY 661 RHAT 662 100.0 663 35.14 621 664 622 665 … … 790 833 .. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py 791 834 835 If a timestamp stored in SQLite has a fractional part longer than 6 836 numbers, its value will be truncated to microsecond precision by the 837 timestamp converter. 838 792 839 793 840 .. _sqlite3-controlling-transactions: … … 862 909 863 910 .. literalinclude:: ../includes/sqlite3/ctx_manager.py 911 912 913 Common issues 914 ------------- 915 916 Multithreading 917 ^^^^^^^^^^^^^^ 918 919 Older SQLite versions had issues with sharing connections between threads. 920 That's why the Python module disallows sharing connections and cursors between 921 threads. If you still try to do so, you will get an exception at runtime. 922 923 The only exception is calling the :meth:`~Connection.interrupt` method, which 924 only makes sense to call from a different thread. 925 926 .. rubric:: Footnotes 927 928 .. [#f1] The sqlite3 module is not built with loadable extension support by 929 default, because some platforms (notably Mac OS X) have SQLite libraries 930 which are compiled without this feature. To get loadable extension support, 931 you must modify setup.py and remove the line that sets 932 SQLITE_OMIT_LOAD_EXTENSION. 933
Note:
See TracChangeset
for help on using the changeset viewer.