Mercurial > p > mysql-python > mysqldb-2
comparison doc/MySQLdb.txt @ 0:e48810735f11 MySQLdb
Copying 1.2.1 to be the new trunk
author | adustman |
---|---|
date | Sun, 02 Apr 2006 18:20:53 +0000 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:e48810735f11 |
---|---|
1 ==================== | |
2 MySQLdb User's Guide | |
3 ==================== | |
4 | |
5 .. contents:: | |
6 .. | |
7 | |
8 Introduction | |
9 ------------ | |
10 | |
11 MySQLdb is an thread-compatible interface to the popular MySQL | |
12 database server that provides the Python database API. | |
13 | |
14 Installation | |
15 ------------ | |
16 | |
17 The ``README`` file has complete installation instructions. | |
18 | |
19 | |
20 _mysql | |
21 ------ | |
22 | |
23 If you want to write applications which are portable across databases, | |
24 use MySQLdb_, and avoid using this module directly. ``_mysql`` | |
25 provides an interface which mostly implements the MySQL C API. For | |
26 more information, see the `MySQL documentation`_. The documentation | |
27 for this module is intentionally weak because you probably should use | |
28 the higher-level MySQLdb module. If you really need it, use the | |
29 standard MySQL docs and transliterate as necessary. | |
30 | |
31 .. _`MySQL documentation`: http://dev.mysql.com/doc/ | |
32 | |
33 | |
34 MySQL C API translation | |
35 ....................... | |
36 | |
37 The MySQL C API has been wrapped in an object-oriented way. The only | |
38 MySQL data structures which are implemented are the ``MYSQL`` | |
39 (database connection handle) and ``MYSQL_RES`` (result handle) | |
40 types. In general, any function which takes ``MYSQL *mysql`` as an | |
41 argument is now a method of the connection object, and any function | |
42 which takes ``MYSQL_RES *result`` as an argument is a method of the | |
43 result object. Functions requiring none of the MySQL data structures | |
44 are implemented as functions in the module. Functions requiring one of | |
45 the other MySQL data structures are generally not implemented. | |
46 Deprecated functions are not implemented. In all cases, the ``mysql_`` | |
47 prefix is dropped from the name. Most of the ``conn`` methods listed | |
48 are also available as MySQLdb Connection object methods. Their use is | |
49 non-portable. | |
50 | |
51 MySQL C API function mapping | |
52 ............................ | |
53 | |
54 =================================== ================================== | |
55 C API ``_mysql`` | |
56 =================================== ================================== | |
57 ``mysql_affected_rows()`` ``conn.affected_rows()`` | |
58 ``mysql_autocommit()`` ``conn.autocommit()`` | |
59 ``mysql_character_set_name()`` ``conn.character_set_name()`` | |
60 ``mysql_close()`` ``conn.close()`` | |
61 ``mysql_commit()`` ``conn.commit()`` | |
62 ``mysql_connect()`` ``_mysql.connect()`` | |
63 ``mysql_data_seek()`` ``result.data_seek()`` | |
64 ``mysql_debug()`` ``_mysql.debug()`` | |
65 ``mysql_dump_debug_info`` ``conn.dump_debug_info()`` | |
66 ``mysql_escape_string()`` ``_mysql.escape_string()`` | |
67 ``mysql_fetch_row()`` ``result.fetch_row()`` | |
68 ``mysql_get_character_set_info()`` ``conn.get_character_set_info()`` | |
69 ``mysql_get_client_info()`` ``_mysql.get_client_info()`` | |
70 ``mysql_get_host_info()`` ``conn.get_host_info()`` | |
71 ``mysql_get_proto_info()`` ``conn.get_proto_info()`` | |
72 ``mysql_get_server_info()`` ``conn.get_server_info()`` | |
73 ``mysql_info()`` ``conn.info()`` | |
74 ``mysql_insert_id()`` ``conn.insert_id()`` | |
75 ``mysql_num_fields()`` ``result.num_fields()`` | |
76 ``mysql_num_rows()`` ``result.num_rows()`` | |
77 ``mysql_options()`` various options to ``_mysql.connect()`` | |
78 ``mysql_ping()`` ``conn.ping()`` | |
79 ``mysql_query()`` ``conn.query()`` | |
80 ``mysql_real_connect()`` ``_mysql.connect()`` | |
81 ``mysql_real_query()`` ``conn.query()`` | |
82 ``mysql_real_escape_string()`` ``conn.escape_string()`` | |
83 ``mysql_rollback()`` ``conn.rollback()`` | |
84 ``mysql_row_seek()`` ``result.row_seek()`` | |
85 ``mysql_row_tell()`` ``result.row_tell()`` | |
86 ``mysql_select_db()`` ``conn.select_db()`` | |
87 ``mysql_set_character_set()`` ``conn.set_character_set()`` | |
88 ``mysql_ssl_set()`` ``ssl`` option to ``_mysql.connect()`` | |
89 ``mysql_stat()`` ``conn.stat()`` | |
90 ``mysql_store_result()`` ``conn.store_result()`` | |
91 ``mysql_thread_id()`` ``conn.thread_id()`` | |
92 ``mysql_thread_safe_client()`` ``conn.thread_safe_client()`` | |
93 ``mysql_use_result()`` ``conn.use_result()`` | |
94 ``mysql_warning_count()`` ``conn.warning_count()`` | |
95 ``CLIENT_*`` ``MySQLdb.constants.CLIENT.*`` | |
96 ``CR_*`` ``MySQLdb.constants.CR.*`` | |
97 ``ER_*`` ``MySQLdb.constants.ER.*`` | |
98 ``FIELD_TYPE_*`` ``MySQLdb.constants.FIELD_TYPE.*`` | |
99 ``FLAG_*`` ``MySQLdb.constants.FLAG.*`` | |
100 =================================== ================================== | |
101 | |
102 | |
103 Some _mysql examples | |
104 .................... | |
105 | |
106 Okay, so you want to use ``_mysql`` anyway. Here are some examples. | |
107 | |
108 The simplest possible database connection is:: | |
109 | |
110 import _mysql | |
111 db=_mysql.connect() | |
112 | |
113 This creates a connection to the MySQL server running on the local | |
114 machine using the standard UNIX socket (or named pipe on Windows), | |
115 your login name (from the USER environment variable), no password, and | |
116 does not ``USE`` a database. Chances are you need to supply more | |
117 information.:: | |
118 | |
119 db=_mysql.connect("localhost","joebob","moonpie","thangs") | |
120 | |
121 This creates a connection to the MySQL server running on the local | |
122 machine via a UNIX socket (or named pipe), the user name "joebob", the | |
123 password "moonpie", and selects the initial database "thangs". | |
124 | |
125 We haven't even begun to touch upon all the parameters ``connect()`` | |
126 can take. For this reason, I prefer to use keyword parameters:: | |
127 | |
128 db=_mysql.connect(host="localhost",user="joebob", | |
129 passwd="moonpie",db="thangs") | |
130 | |
131 This does exactly what the last example did, but is arguably easier to | |
132 read. But since the default host is "localhost", and if your login | |
133 name really was "joebob", you could shorten it to this:: | |
134 | |
135 db=_mysql.connect(passwd="moonpie",db="thangs") | |
136 | |
137 UNIX sockets and named pipes don't work over a network, so if you | |
138 specify a host other than localhost, TCP will be used, and you can | |
139 specify an odd port if you need to (the default port is 3306):: | |
140 | |
141 db=_mysql.connect(host="outhouse",port=3307,passwd="moonpie",db="thangs") | |
142 | |
143 If you really had to, you could connect to the local host with TCP by | |
144 specifying the full host name, or 127.0.0.1. | |
145 | |
146 Generally speaking, putting passwords in your code is not such a good | |
147 idea:: | |
148 | |
149 db=_mysql.connect(host="outhouse",db="thangs",read_default_file="~/.my.cnf") | |
150 | |
151 This does what the previous example does, but gets the username and | |
152 password and other parameters from ~/.my.cnf (UNIX-like systems). Read | |
153 about `option files`_ for more details. | |
154 | |
155 .. _`option files`: http://dev.mysql.com/doc/mysql/en/Option_files.html | |
156 | |
157 So now you have an open connection as ``db`` and want to do a | |
158 query. Well, there are no cursors in MySQL, and no parameter | |
159 substitution, so you have to pass a complete query string to | |
160 ``db.query()``:: | |
161 | |
162 db.query("""SELECT spam, eggs, sausage FROM breakfast | |
163 WHERE price < 5""") | |
164 | |
165 There's no return value from this, but exceptions can be raised. The | |
166 exceptions are defined in a separate module, ``_mysql_exceptions``, | |
167 but ``_mysql`` exports them. Read DB API specification PEP-249_ to | |
168 find out what they are, or you can use the catch-all ``MySQLError``. | |
169 | |
170 .. _PEP-249: http://www.python.org/peps/pep-0249.html | |
171 | |
172 At this point your query has been executed and you need to get the | |
173 results. You have two options:: | |
174 | |
175 r=db.store_result() | |
176 # ...or... | |
177 r=db.use_result() | |
178 | |
179 Both methods return a result object. What's the difference? | |
180 ``store_result()`` returns the entire result set to the client | |
181 immediately. If your result set is really large, this could be a | |
182 problem. One way around this is to add a ``LIMIT`` clause to your | |
183 query, to limit the number of rows returned. The other is to use | |
184 ``use_result()``, which keeps the result set in the server and sends | |
185 it row-by-row when you fetch. This does, however, tie up server | |
186 resources, and it ties up the connection: You cannot do any more | |
187 queries until you have fetched **all** the rows. Generally I | |
188 recommend using ``store_result()`` unless your result set is really | |
189 huge and you can't use ``LIMIT`` for some reason. | |
190 | |
191 Now, for actually getting real results:: | |
192 | |
193 >>> r.fetch_row() | |
194 (('3','2','0'),) | |
195 | |
196 This might look a little odd. The first thing you should know is, | |
197 ``fetch_row()`` takes some additional parameters. The first one is, | |
198 how many rows (``maxrows``) should be returned. By default, it returns | |
199 one row. It may return fewer rows than you asked for, but never | |
200 more. If you set ``maxrows=0``, it returns all rows of the result | |
201 set. If you ever get an empty tuple back, you ran out of rows. | |
202 | |
203 The second parameter (``how``) tells it how the row should be | |
204 represented. By default, it is zero which means, return as a tuple. | |
205 ``how=1`` means, return it as a dictionary, where the keys are the | |
206 column names, or ``table.column`` if there are two columns with the | |
207 same name (say, from a join). ``how=2`` means the same as ``how=1`` | |
208 except that the keys are *always* ``table.column``; this is for | |
209 compatibility with the old ``Mysqldb`` module. | |
210 | |
211 OK, so why did we get a 1-tuple with a tuple inside? Because we | |
212 implicitly asked for one row, since we didn't specify ``maxrows``. | |
213 | |
214 The other oddity is: Assuming these are numeric columns, why are they | |
215 returned as strings? Because MySQL returns all data as strings and | |
216 expects you to convert it yourself. This would be a real pain in the | |
217 ass, but in fact, ``_mysql`` can do this for you. (And ``MySQLdb`` | |
218 does do this for you.) To have automatic type conversion done, you | |
219 need to create a type converter dictionary, and pass this to | |
220 ``connect()`` as the ``conv`` keyword parameter. | |
221 | |
222 The keys of ``conv`` should be MySQL column types, which in the | |
223 C API are ``FIELD_TYPE_*``. You can get these values like this:: | |
224 | |
225 from MySQLdb.constants import FIELD_TYPE | |
226 | |
227 By default, any column type that can't be found in ``conv`` is | |
228 returned as a string, which works for a lot of stuff. For our | |
229 purposes, we probably want this:: | |
230 | |
231 my_conv = { FIELD_TYPE.LONG: int } | |
232 | |
233 This means, if it's a ``FIELD_TYPE_LONG``, call the builtin ``int()`` | |
234 function on it. Note that ``FIELD_TYPE_LONG`` is an ``INTEGER`` | |
235 column, which corresponds to a C ``long``, which is also the type used | |
236 for a normal Python integer. But beware: If it's really an ``UNSIGNED | |
237 INTEGER`` column, this could cause overflows. For this reason, | |
238 ``MySQLdb`` actually uses ``long()`` to do the conversion. But we'll | |
239 ignore this potential problem for now. | |
240 | |
241 Then if you use ``db=_mysql.connect(conv=my_conv...)``, the | |
242 results will come back ``((3, 2, 0),)``, which is what you would | |
243 expect. | |
244 | |
245 MySQLdb | |
246 ------- | |
247 | |
248 MySQLdb is a thin Python wrapper around ``_mysql`` which makes it | |
249 compatible with the Python DB API interface (version 2). In reality, | |
250 a fair amount of the code which implements the API is in ``_mysql`` | |
251 for the sake of efficiency. | |
252 | |
253 The DB API specification PEP-249_ should be your primary guide for | |
254 using this module. Only deviations from the spec and other | |
255 database-dependent things will be documented here. | |
256 | |
257 Functions and attributes | |
258 ........................ | |
259 | |
260 Only a few top-level functions and attributes are defined within | |
261 MySQLdb. | |
262 | |
263 connect(parameters...) | |
264 Constructor for creating a connection to the | |
265 database. Returns a Connection Object. Parameters are the | |
266 same as for the MySQL C API. In addition, there are a few | |
267 additional keywords that correspond to what you would pass | |
268 ``mysql_options()`` before connecting. Note that some | |
269 parameters must be specified as keyword arguments! The | |
270 default value for each parameter is NULL or zero, as | |
271 appropriate. Consult the MySQL documentation for more | |
272 details. The important parameters are: | |
273 | |
274 host | |
275 name of host to connect to. Default: use the local host | |
276 via a UNIX socket (where applicable) | |
277 | |
278 user | |
279 user to authenticate as. Default: current effective user. | |
280 | |
281 passwd | |
282 password to authenticate with. Default: no password. | |
283 | |
284 db | |
285 database to use. Default: no default database. | |
286 | |
287 port | |
288 TCP port of MySQL server. Default: standard port (3306). | |
289 | |
290 unix_socket | |
291 location of UNIX socket. Default: use default location or | |
292 TCP for remote hosts. | |
293 | |
294 conv | |
295 type conversion dictionary. Default: a copy of | |
296 ``MySQLdb.converters.conversions`` | |
297 | |
298 compress | |
299 Enable protocol compression. Default: no compression. | |
300 | |
301 connect_timeout | |
302 Abort if connect is not completed within | |
303 given number of seconds. Default: no timeout (?) | |
304 | |
305 named_pipe | |
306 Use a named pipe (Windows). Default: don't. | |
307 | |
308 init_command | |
309 Initial command to issue to server upon | |
310 connection. Default: Nothing. | |
311 | |
312 read_default_file | |
313 MySQL configuration file to read; see | |
314 the MySQL documentation for ``mysql_options()``. | |
315 | |
316 read_default_group | |
317 Default group to read; see the MySQL | |
318 documentation for ``mysql_options()``. | |
319 | |
320 cursorclass | |
321 cursor class that ``cursor()`` uses, unless | |
322 overridden. Default: ``MySQLdb.cursors.Cursor``. *This | |
323 must be a keyword parameter.* | |
324 | |
325 use_unicode | |
326 If True, CHAR and VARCHAR and TEXT columns are returned as | |
327 Unicode strings, using the configured character set. It is | |
328 best to set the default encoding in the server | |
329 configuration, or client configuration (read with | |
330 read_default_file). If you change the character set after | |
331 connecting (MySQL-4.1 and later), you'll need to put the | |
332 correct character set name in connection.charset. | |
333 | |
334 If False, text-like columns are returned as normal strings, | |
335 but you can always write Unicode strings. | |
336 | |
337 *This must be a keyword parameter.* | |
338 | |
339 charset | |
340 If present, the connection character set will be changed | |
341 to this character set, if they are not equal. Support for | |
342 changing the character set requires MySQL-4.1 and later | |
343 server; if the server is too old, UnsupportedError will be | |
344 raised. This option implies use_unicode=True, but you can | |
345 override this with use_unicode=False, though you probably | |
346 shouldn't. | |
347 | |
348 If not present, the default character set is used. | |
349 | |
350 *This must be a keyword parameter.* | |
351 | |
352 sql_mode | |
353 If present, the session SQL mode will be set to the given | |
354 string. For more information on sql_mode, see the MySQL | |
355 documentation. Only available for 4.1 and newer servers. | |
356 | |
357 If not present, the session SQL mode will be unchanged. | |
358 | |
359 *This must be a keyword parameter.* | |
360 | |
361 ssl | |
362 This parameter takes a dictionary or mapping, where the | |
363 keys are parameter names used by the mysql_ssl_set_ MySQL | |
364 C API call. If this is set, it initiates an SSL connection | |
365 to the server; if there is no SSL support in the client, | |
366 an exception is raised. *This must be a keyword | |
367 parameter.* | |
368 | |
369 .. _mysql_ssl_set: http://dev.mysql.com/doc/mysql/en/mysql_ssl_set.html | |
370 | |
371 | |
372 apilevel | |
373 String constant stating the supported DB API level. '2.0' | |
374 | |
375 threadsafety | |
376 Integer constant stating the level of thread safety the | |
377 interface supports. This is set to 1, which means: Threads may | |
378 share the module. | |
379 | |
380 The MySQL protocol can not handle multiple threads using the | |
381 same connection at once. Some earlier versions of MySQLdb | |
382 utilized locking to achieve a threadsafety of 2. While this is | |
383 not terribly hard to accomplish using the standard Cursor class | |
384 (which uses ``mysql_store_result()``), it is complicated by | |
385 SSCursor (which uses ``mysql_use_result()``; with the latter you | |
386 must ensure all the rows have been read before another query can | |
387 be executed. It is further complicated by the addition of | |
388 transactions, since transactions start when a cursor execute a | |
389 query, but end when ``COMMIT`` or ``ROLLBACK`` is executed by | |
390 the Connection object. Two threads simply cannot share a | |
391 connection while a transaction is in progress, in addition to | |
392 not being able to share it during query execution. This | |
393 excessively complicated the code to the point where it just | |
394 isn't worth it. | |
395 | |
396 The general upshot of this is: Don't share connections between | |
397 threads. It's really not worth your effort or mine, and in the | |
398 end, will probably hurt performance, since the MySQL server runs | |
399 a separate thread for each connection. You can certainly do | |
400 things like cache connections in a pool, and give those | |
401 connections to one thread at a time. If you let two threads use | |
402 a connection simultaneously, the MySQL client library will | |
403 probably upchuck and die. You have been warned. | |
404 | |
405 For threaded applications, try using a connection pool. | |
406 This can be done using the `Pool module`_. | |
407 | |
408 .. _`Pool module`: http://dustman.net/andy/python/Pool | |
409 | |
410 charset | |
411 The character set used by the connection. In MySQL-4.1 and newer, | |
412 it is possible (but not recommended) to change the connection's | |
413 character set with an SQL statement. If you do this, you'll also | |
414 need to change this attribute. Otherwise, you'll get encoding | |
415 errors. | |
416 | |
417 paramstyle | |
418 String constant stating the type of parameter marker formatting | |
419 expected by the interface. Set to 'format' = ANSI C printf | |
420 format codes, e.g. '...WHERE name=%s'. If a mapping object is | |
421 used for conn.execute(), then the interface actually uses | |
422 'pyformat' = Python extended format codes, e.g. '...WHERE | |
423 name=%(name)s'. However, the API does not presently allow the | |
424 specification of more than one style in paramstyle. | |
425 | |
426 Note that any literal percent signs in the query string passed | |
427 to execute() must be escaped, i.e. %%. | |
428 | |
429 Parameter placeholders can **only** be used to insert column | |
430 values. They can **not** be used for other parts of SQL, such as | |
431 table names, statements, etc. | |
432 | |
433 conv | |
434 A dictionary or mapping which controls how types are converted | |
435 from MySQL to Python and vice versa. | |
436 | |
437 If the key is a MySQL type (from ``FIELD_TYPE.*``), then the value | |
438 can be either: | |
439 | |
440 * a callable object which takes a string argument (the MySQL | |
441 value),' returning a Python value | |
442 | |
443 * a sequence of 2-tuples, where the first value is a combination | |
444 of flags from ``MySQLdb.constants.FLAG``, and the second value | |
445 is a function as above. The sequence is tested until the flags | |
446 on the field match those of the first value. If both values | |
447 are None, then the default conversion is done. Presently this | |
448 is only used to distinquish TEXT and BLOB columns. | |
449 | |
450 If the key is a Python type or class, then the value is a | |
451 callable Python object (usually a function) taking two arguments | |
452 (value to convert, and the conversion dictionary) which converts | |
453 values of this type to a SQL literal string value. | |
454 | |
455 This is initialized with reasonable defaults for most | |
456 types. When creating a Connection object, you can pass your own | |
457 type converter dictionary as a keyword parameter. Otherwise, it | |
458 uses a copy of ``MySQLdb.converters.conversions``. Several | |
459 non-standard types are returned as strings, which is how MySQL | |
460 returns all columns. For more details, see the built-in module | |
461 documentation. | |
462 | |
463 | |
464 Connection Objects | |
465 .................. | |
466 | |
467 Connection objects are returned by the ``connect()`` function. | |
468 | |
469 commit() | |
470 If the database and the tables support transactions, this | |
471 commits the current transaction; otherwise this method | |
472 successfully does nothing. | |
473 | |
474 rollback() | |
475 If the database and tables support transactions, this rolls back | |
476 (cancels) the current transaction; otherwise a | |
477 ``NotSupportedError`` is raised. | |
478 | |
479 cursor([cursorclass]) | |
480 MySQL does not support cursors; however, cursors are easily | |
481 emulated. You can supply an alternative cursor class as an | |
482 optional parameter. If this is not present, it defaults to the | |
483 value given when creating the connection object, or the standard | |
484 ``Cursor`` class. Also see the additional supplied cursor | |
485 classes in the usage section. | |
486 | |
487 There are many more methods defined on the connection object which | |
488 are MySQL-specific. For more information on them, consult the internal | |
489 documentation using ``pydoc``. | |
490 | |
491 | |
492 Cursor Objects | |
493 .............. | |
494 | |
495 callproc(procname, args) | |
496 Calls stored procedure procname with the sequence of arguments | |
497 in args. Returns the original arguments. Stored procedure | |
498 support only works with MySQL-5.0 and newer. | |
499 | |
500 **Compatibility note:** PEP-249_ specifies that if there are | |
501 OUT or INOUT parameters, the modified values are to be | |
502 returned. This is not consistently possible with MySQL. Stored | |
503 procedure arguments must be passed as server variables, and | |
504 can only be returned with a SELECT statement. Since a stored | |
505 procedure may return zero or more result sets, it is impossible | |
506 for MySQLdb to determine if there are result sets to fetch | |
507 before the modified parmeters are accessible. | |
508 | |
509 The parameters are stored in the server as @_*procname*_*n*, | |
510 where *n* is the position of the parameter. I.e., if you | |
511 cursor.callproc('foo', (a, b, c)), the parameters will be | |
512 accessible by a SELECT statement as @_foo_0, @_foo_1, and | |
513 @_foo_2. | |
514 | |
515 **Compatibility note:** It appears that the mere act of | |
516 executing the CALL statement produces an empty result set, which | |
517 appears after any result sets which might be generated by the | |
518 stored procedure. Thus, you will always need to use nextset() to | |
519 advance result sets. | |
520 | |
521 close() | |
522 Closes the cursor. Future operations raise ``ProgrammingError``. | |
523 If you are using server-side cursors, it is very important to | |
524 close the cursor when you are done with it and before creating a | |
525 new one. | |
526 | |
527 info() | |
528 Returns some information about the last query. Normally | |
529 you don't need to check this. If there are any MySQL | |
530 warnings, it will cause a Warning to be issued through | |
531 the Python warning module. By default, Warning causes a | |
532 message to appear on the console. However, it is possible | |
533 to filter these out or cause Warning to be raised as exception. | |
534 See the MySQL docs for ``mysql_info()``, and the Python warning | |
535 module. (Non-standard) | |
536 | |
537 setinputsizes() | |
538 Does nothing, successfully. | |
539 | |
540 setoutputsizes() | |
541 Does nothing, successfully. | |
542 | |
543 nextset() | |
544 Advances the cursor to the next result set, discarding the remaining | |
545 rows in the current result set. If there are no additional result | |
546 sets, it returns None; otherwise it returns a true value. | |
547 | |
548 Note that MySQL doesn't support multiple result sets until 4.1. | |
549 | |
550 | |
551 Some examples | |
552 ............. | |
553 | |
554 The ``connect()`` method works nearly the same as with `_mysql`_:: | |
555 | |
556 import MySQLdb | |
557 db=MySQLdb.connect(passwd="moonpie",db="thangs") | |
558 | |
559 To perform a query, you first need a cursor, and then you can execute | |
560 queries on it:: | |
561 | |
562 c=db.cursor() | |
563 max_price=5 | |
564 c.execute("""SELECT spam, eggs, sausage FROM breakfast | |
565 WHERE price < %s""", (max_price,)) | |
566 | |
567 In this example, ``max_price=5`` Why, then, use ``%s`` in the | |
568 string? Because MySQLdb will convert it to a SQL literal value, which | |
569 is the string '5'. When it's finished, the query will actually say, | |
570 "...WHERE price < 5". | |
571 | |
572 Why the tuple? Because the DB API requires you to pass in any | |
573 parameters as a sequence. Due to the design of the parser, (max_price) | |
574 is interpreted as using algebraic grouping and simply as max_price and | |
575 not a tuple. Adding a comma, i.e. (max_price,) forces it to make a | |
576 tuple. | |
577 | |
578 And now, the results:: | |
579 | |
580 >>> c.fetchone() | |
581 (3L, 2L, 0L) | |
582 | |
583 Quite unlike the ``_mysql`` example, this returns a single tuple, | |
584 which is the row, and the values are properly converted by default... | |
585 except... What's with the L's? | |
586 | |
587 As mentioned earlier, while MySQL's INTEGER column translates | |
588 perfectly into a Python integer, UNSIGNED INTEGER could overflow, so | |
589 these values are converted to Python long integers instead. | |
590 | |
591 If you wanted more rows, you could use ``c.fetchmany(n)`` or | |
592 ``c.fetchall()``. These do exactly what you think they do. On | |
593 ``c.fetchmany(n)``, the ``n`` is optional and defaults to | |
594 ``c.arraysize``, which is normally 1. Both of these methods return a | |
595 sequence of rows, or an empty sequence if there are no more rows. If | |
596 you use a weird cursor class, the rows themselves might not be tuples. | |
597 | |
598 Note that in contrast to the above, ``c.fetchone()`` returns ``None`` | |
599 when there are no more rows to fetch. | |
600 | |
601 The only other method you are very likely to use is when you have to | |
602 do a multi-row insert:: | |
603 | |
604 c.executemany( | |
605 """INSERT INTO breakfast (name, spam, eggs, sausage, price) | |
606 VALUES (%s, %s, %s, %s, %s)""", | |
607 [ | |
608 ("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ), | |
609 ("Not So Much Spam Plate", 3, 2, 0, 3.95 ), | |
610 ("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 ) | |
611 ] ) | |
612 | |
613 Here we are inserting three rows of five values. Notice that there is | |
614 a mix of types (strings, ints, floats) though we still only use | |
615 ``%s``. And also note that we only included format strings for one | |
616 row. MySQLdb picks those out and duplicates them for each row. | |
617 | |
618 Using and extending | |
619 ------------------- | |
620 | |
621 In general, it is probably wise to not directly interact with the DB | |
622 API except for small applicatons. Databases, even SQL databases, vary | |
623 widely in capabilities and may have non-standard features. The DB API | |
624 does a good job of providing a reasonably portable interface but some | |
625 methods are non-portable. Specifically, the parameters accepted by | |
626 ``connect()`` are completely implementation-dependent. | |
627 | |
628 If you believe your application may need to run on several different | |
629 databases, the author recommends the following approach, based on | |
630 personal experience: Write a simplified API for your application which | |
631 implements the specific queries and operations your application needs | |
632 to perform. Implement this API as a base class which should be have | |
633 few database dependencies, and then derive a subclass from this which | |
634 implements the necessary dependencies. In this way, porting your | |
635 application to a new database should be a relatively simple matter of | |
636 creating a new subclass, assuming the new database is reasonably | |
637 standard. | |
638 | |
639 Because MySQLdb's Connection and Cursor objects are written in Python, | |
640 you can easily derive your own subclasses. There are several Cursor | |
641 classes in MySQLdb.cursors: | |
642 | |
643 BaseCursor | |
644 The base class for Cursor objects. This does not raise Warnings. | |
645 | |
646 CursorStoreResultMixIn | |
647 Causes the Cursor to use the ``mysql_store_result()`` function to | |
648 get the query result. The entire result set is stored on the | |
649 client side. | |
650 | |
651 CursorUseResultMixIn | |
652 Causes the cursor to use the ``mysql_use_result()`` function to | |
653 get the query result. The result set is stored on the server side | |
654 and is transferred row by row using fetch operations. | |
655 | |
656 CursorTupleRowsMixIn | |
657 Causes the cursor to return rows as a tuple of the column values. | |
658 | |
659 CursorDictRowsMixIn | |
660 | |
661 Causes the cursor to return rows as a dictionary, where the keys | |
662 are column names and the values are column values. Note that if | |
663 the column names are not unique, i.e., you are selecting from two | |
664 tables that share column names, some of them will be rewritten as | |
665 ``table.column``. This can be avoided by using the SQL ``AS`` | |
666 keyword. (This is yet-another reason not to use ``*`` in SQL | |
667 queries, particularly where ``JOIN`` is involved.) | |
668 | |
669 Cursor | |
670 The default cursor class. This class is composed of | |
671 ``CursorWarningMixIn``, ``CursorStoreResultMixIn``, | |
672 ``CursorTupleRowsMixIn,`` and ``BaseCursor``, i.e. it raises | |
673 ``Warning``, uses ``mysql_store_result()``, and returns rows as | |
674 tuples. | |
675 | |
676 DictCursor | |
677 Like ``Cursor`` except it returns rows as dictionaries. | |
678 | |
679 SSCursor | |
680 A "server-side" cursor. Like ``Cursor`` but uses | |
681 ``CursorUseResultMixIn``. Use only if you are dealing with | |
682 potentially large result sets. | |
683 | |
684 SSDictCursor | |
685 Like ``SSCursor`` except it returns rows as dictionaries. | |
686 | |
687 | |
688 Embedded Server | |
689 --------------- | |
690 | |
691 Instead of connecting to a stand-alone server over the network, | |
692 the embedded server support lets you run a full server right in | |
693 your Python code or application server. | |
694 | |
695 If you have built MySQLdb with embedded server support, there | |
696 are two additional functions you will need to make use of: | |
697 | |
698 server_init(args, groups) | |
699 Initialize embedded server. If this client is not linked against | |
700 the embedded server library, this function does nothing. | |
701 | |
702 args | |
703 sequence of command-line arguments | |
704 groups | |
705 sequence of groups to use in defaults files | |
706 | |
707 server_end() | |
708 Shut down embedded server. If not using an embedded server, this | |
709 does nothing. | |
710 | |
711 See the MySQL documentation for more information on the embedded | |
712 server. | |
713 | |
714 | |
715 | |
716 :Title: MySQLdb: a Python interface for MySQL | |
717 :Author: Andy Dustman | |
718 :Version: $Revision$ |