File: MySQLdb-3.html

package info (click to toggle)
python-mysqldb 0.9.1-3
  • links: PTS
  • area: main
  • in suites: woody
  • size: 364 kB
  • ctags: 712
  • sloc: ansic: 1,428; python: 1,098; makefile: 59; sh: 28
file content (316 lines) | stat: -rw-r--r-- 13,176 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
 <META NAME="GENERATOR" CONTENT="SGML-Tools 1.0.9">
 <TITLE>MySQLdb: a Python interface for MySQL: MySQLdb -- DB API interface</TITLE>
 <LINK HREF="MySQLdb-4.html" REL=next>
 <LINK HREF="MySQLdb-2.html" REL=previous>
 <LINK HREF="MySQLdb.html#toc3" REL=contents>
</HEAD>
<BODY>
<A HREF="MySQLdb-4.html">Next</A>
<A HREF="MySQLdb-2.html">Previous</A>
<A HREF="MySQLdb.html#toc3">Contents</A>
<HR>
<H2><A NAME="MySQLdb"></A> <A NAME="s3">3. MySQLdb -- DB API interface</A></H2>

<P>MySQLdb is a thin Python wrapper around <CODE>
<A HREF="MySQLdb-2.html#_mysql">_mysql</A>
</CODE>
which makes it compatible with the Python DB API interface (version
2).  In reality, a fair amount of the code which implements the API is
in <CODE>_mysql</CODE> for the sake of efficiency.
<P>The 
<A HREF="http://www.python.org/topics/database/DatabaseAPI-2.0.html">DB API specification</A> should be your primary guide for using
this module. Only deviations from the spec and other
database-dependent things will be documented here.
<P>
<H2><A NAME="ss3.1">3.1 Functions and attributes </A>
</H2>

<P>Only a few top-level functions and attributes are defined within
MySQLdb.
<P>
<DL>
<DT><B>
<A NAME="connect()"></A> connect(parameters...)</B><DD><P>Constructor
for creating a connection to the database. Returns a Connection
Object. Parameters are the same as for the MySQL C API.  In
addition, there are a few additional keywords that correspond to
what you would pass <CODE>mysql_options()</CODE> before connecting. Note
that some parameters must be specified as keyword arguments! The
default value for each parameter is NULL or zero, as
appropriate. Consult the MySQL documentation for more
details. The important parameters are:
<P>
<DL>
<DT><B>host</B><DD><P>name of host to connect to. Default: use local host 
<P>
<DT><B>user</B><DD><P>user to authenticate as. Default: current effective user.
<P>
<DT><B>passwd</B><DD><P>password to authenticate with. Default: no password.
<P>
<DT><B>db</B><DD><P>database to use. Default: no default database.
<P>
<DT><B>port</B><DD><P>TCP port of MySQL server. Default: standard port (3306).
<P>
<DT><B>unix_socket</B><DD><P>location of UNIX socket. Default: use TCP.
<P>
<DT><B>conv</B><DD><P>type conversion dictionary.
Default: a copy of <CODE>MySQLdb.converters.conversions</CODE>
<P>
<DT><B>compress</B><DD><P>Enable protocol compression. Default: no compression.
<P>
<DT><B>connect_timeout</B><DD><P>Abort if connect is not completed within
given number of seconds. Default: no timeout (?)
<P>
<DT><B>named_pipe</B><DD><P>Use a named pipe (Windows). Default: don't.
<P>
<DT><B>init_command</B><DD><P>Initial command to issue to server upon
connection. Default: Nothing.
<P>
<DT><B>read_default_file</B><DD><P>MySQL configuration file to read; see
the MySQL documentation for <CODE>mysql_options()</CODE>.
<P>
<DT><B>read_default_group</B><DD><P>Default group to read; see the MySQL
documentation for <CODE>mysql_options()</CODE>.
<P>
<DT><B>cursorclass</B><DD><P>cursor class that <CODE>cursor()</CODE> uses,
unless overridden. Default: <CODE>MySQLdb.cursors.Cursor</CODE>.
<EM>This must be a keyword parameter.</EM>
<P>
</DL>
<P>
<DT><B>apilevel</B><DD><P>String constant stating the supported DB API level. '2.0'
<P>
<DT><B>threadsafety</B><DD><P>Integer constant stating the level of thread
safety the interface supports. As of MySQLdb version 0.9.0, this
is set to 1, which means: Threads may share the module.
<P>The MySQL protocol can not handle multiple threads using the
same connection at once. Some earlier versions of MySQLdb utilized locking
to achieve a threadsafety of 2. While this is not terribly hard
to accomplish using the standard Cursor class (which uses
<CODE>mysql_store_result()</CODE>), it is complicated by SSCursor (which
uses <CODE>mysql_use_result()</CODE>; with the latter you must ensure
all the rows have been read before another query can be executed.
It is further complicated by the addition of transactions, since
transactions start when a cursor execute a query, but end when
<CODE>COMMIT</CODE> or <CODE>ROLLBACK</CODE> is executed by the Connection object.
Two threads cannot share a connection while a transaction is in
progress, in addition to not being able to share it during query
execution. This excessively complicated the code to the point where
it just isn't worth it. 
<P>The general upshot of this is: Don't
share connections between threads. It's really not worth your effort
or mine, and in the end, will probably hurt performance, since the MySQL
server runs a separate thread for each connection.
You can certainly do things like
cache connections in a pool, and give those connections to one
thread at a time. If you let two threads use a connection simultaneously,
the MySQL client library will probably upchuck and die.
You have been warned.
<P>
<DT><B>paramstyle</B><DD><P>String constant stating the type of parameter
marker formatting expected by the interface. Set to 'format' =
ANSI C printf format codes, e.g. '...WHERE name=%s'. If a
mapping object is used for conn.execute(), then the interface
actually uses 'pyformat' = Python extended format codes,
e.g. '...WHERE name=%(name)s'. However, the API does not
presently allow the specification of more than one style in
paramstyle.
<P>Compatibility note: The older MySQLmodule uses a similar
parameter scheme, but requires that quotes be placed around
format strings which will contain strings, dates, and similar
character data. This is not necessary for MySQLdb. It is
recommended that %s (and not '%s') be used for all parameters,
regardless of type. The interface performs all necessary
quoting.
<P>
<DT><B>
<A NAME="conversions"></A> conv</B><DD><P>A dictionary mapping MySQL types
(from <CODE>FIELD_TYPE.*</CODE>) to callable Python objects (usually
functions) which convert from a string to the desired type; and
mapping Python types to callable Python objects which convert
values of this type to a SQL literal string value. This is
initialized with reasonable defaults for most types. When
creating a Connection object, you can pass your own type
converter dictionary as a keyword parameter. Otherwise, it uses
a copy of <CODE>MySQLdb.converters.conversions</CODE>. The dictionary
includes some of the factory functions from the
<CODE>DateTime</CODE> module, if it is available. Several
non-standard types are returned as strings,
which is how MySQL returns all columns. For more details, see
the built-in module documentation.
<P>
<P>As of MySQL-3.23, MySQL supports different character sets in the
server, and a new quoting function, <CODE>mysql_real_escape_string()</CODE>.
This requires the string quoting function to be a method bound to
the connection object. MySQLdb handles this for you automatically.
However, if you feel the need to do something goofy with your strings,
you will have to modify the dictionary after opening the connection.
In practice, you should never have to worry about this.
<P>
</DL>
<P>
<H2><A NAME="ss3.2">3.2 Connection Objects</A>
</H2>

<P>Connection objects are returned by the <CODE>connect()</CODE> function.
<DL>
<P>
<DT><B>commit()</B><DD><P>If the database and the tables support
transactions, this commits the current transaction; otherwise
this method successfully does nothing.
<P>
<DT><B>
<A NAME="rollback"></A> rollback()</B><DD><P>If the database and tables
support transactions, this rolls back (cancels) the current
transaction; otherwise a <CODE>NotSupportedError</CODE> is raised.
<P>Compatibility note: The older 
<A HREF="MySQLdb-1.html#MySQLmodule">MySQLmodule</A>
 defines this method,
which sucessfully does nothing. This is dangerous behavior, as a
successful rollback indicates that the current transaction was
backed out, which is not true, and fails to notify the
programmer that the database now needs to be cleaned up by other
means.
<P>
<DT><B>cursor([cursorclass])</B><DD><P>MySQL does not support cursors;
however, cursors are easily emulated.  You can supply an
alternative cursor class as an optional parameter.  If this is
not present, it defaults to the value given when creating the
connection object, or the standard <CODE>Cursor</CODE> class. Also see
the additional supplied cursor classes in the 
<A HREF="MySQLdb-4.html#usage">usage</A>

section.
<P>
<DT><B>begin()</B><DD><P>Explicitly start a transactions. Normally you do
not need to use this: Executing a query implicitely starts a new
transaction if one is not in progress. If AUTOCOMMIT is on, you
can use <CODE>begin()</CODE> to temporarily turn it off. AUTOCOMMIT will
resume after the next <CODE>commit()</CODE> or <CODE>rollback</CODE>.
<P>
</DL>
<P>
<H2><A NAME="ss3.3">3.3 Cursor Objects</A>
</H2>

<P>
<DL>
<DT><B>callproc()</B><DD><P>Not implemented.
<P>
<DT><B>close()</B><DD><P>Closes the cursor. Future operations raise <CODE>ProgrammingError</CODE>.
If you are using 
<A HREF="MySQLdb-4.html#SSCursor">server-side cursors</A>,
it is very important to close the cursor when you are done with
it and before creating a new one.
<P>
<DT><B>insert_id()</B><DD><P>Returns the last <CODE>AUTO_INCREMENT</CODE> field value inserted
into the database. (Non-standard)
<P>
<DT><B>info()</B><DD><P>Returns some information about the last query. Normally
you don't need to check this. With the default cursor, any MySQL
warnings cause <CODE>Warning</CODE> to be raised. If you are using a
cursor class without warnings, then you might want to use
this. See the MySQL docs for <CODE>mysql_info()</CODE>. (Non-standard)
<P>
<DT><B>setinputsizes()</B><DD><P>Does nothing, successfully.
<P>
<DT><B>setoutputsizes()</B><DD><P>Does nothing, successfully.
<P>
</DL>
<H2><A NAME="ss3.4">3.4 Some examples</A>
</H2>

<P>The <CODE>connect()</CODE> method works nearly the same as with <CODE>_mysql</CODE>:
<HR>
<PRE>
import MySQLdb
db=MySQLdb.connect(passwd="moonpie",db="thangs")
</PRE>
<HR>

To perform a query, you first need a cursor, and then you can execute
queries on it.
<HR>
<PRE>
c=db.cursor()
max_price=5
c.execute("""SELECT spam, eggs, sausage FROM breakfast
            WHERE price &lt; %s""", (max_price,))
</PRE>
<HR>

In this example, <CODE>max_price=5</CODE> Why, then, use <CODE>%s</CODE> in the
string? Because MySQLdb will convert it to a SQL literal value, which
is the string '5'. When it's finished, the query will actually say,
"...WHERE price &lt; 5".
<P>
<P>Why the tuple? Because the DB API requires you to pass in any
parameters as a sequence.
<P>
<P>And now, the results:
<HR>
<PRE>
>>> c.fetchone()
(3L, 2L, 0L)
</PRE>
<HR>

Quite unlike the <CODE>_mysql</CODE> example, this returns a single tuple,
which is the row, and the values are properly converted by default...
except... What's with the L's?
<P>
<P>As mentioned earlier, while MySQL's INTEGER column translates
perfectly into a Python integer, UNSIGNED INTEGER could overflow, so
these values are converted to Python long integers instead. Prior to
Python 1.6, long integers retained the L when converted to strings
with <CODE>str()</CODE>. In 1.6 and later, <CODE>str()</CODE> does not include the L.
Of course, the L always prints when using <CODE>repr()</CODE>, which is what
has happened here.
<P>
<P>When you are finished with a transaction, you should execute either
<CODE>db.commit()</CODE> or <CODE>db.rollback()</CODE>. If your server and tables
don't support transactions, <CODE>commit()</CODE> will still work, but
<CODE>rollback()</CODE> will raise an exception. Note carefully that these are
methods of the <EM>connection</EM> and not methods of the <EM>cursor</EM>,
even though <CODE>c.execute(...)</CODE> is what started the transaction.
<P>
<P>If you wanted more rows, you could use <CODE>c.fetchmany(n)</CODE> or
<CODE>c.fetchall()</CODE>. These do exactly what you think they do. On
<CODE>c.fetchmany(n)</CODE>, the <CODE>n</CODE> is optional and defaults to
<CODE>c.arraysize</CODE>, which is normally 100. Both of these methods return
a sequence of rows, or an empty sequence if there are no more rows.
If you use a weird cursor class, the rows themselves might not be
tuples.
<P>
<P>Note that in contrast to the above, <CODE>c.fetchone()</CODE> returns <CODE>None</CODE>
when there are no more rows to fetch.
<P>
<P>The only other method you are very likely to use is when you have to
do a multi-row insert:
<HR>
<PRE>
c.execute("""INSERT INTO breakfast (name, spam, eggs, sausage, price)
             VALUES (%s, %s, %s, %s, %s)""",
             [ ("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ),
               ("Not So Much Spam Plate", 3, 2, 0, 3.95 ),
               ("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 )
             ]
         )
</PRE>
<HR>

Here we are inserting three rows of five values. Notice that there is
a mix of types (strings, ints, floats) though we still only use
<CODE>%s</CODE>. And also note that we only included format strings for one
row. MySQLdb picks those out and duplicates them for each row.
<BLOCKQUOTE>Baked beans are off!</BLOCKQUOTE>
<P>
<HR>
<A HREF="MySQLdb-4.html">Next</A>
<A HREF="MySQLdb-2.html">Previous</A>
<A HREF="MySQLdb.html#toc3">Contents</A>
</BODY>
</HTML>