Skip to content

Commit c8b2744

Browse files
committed
Merge pull request #12 from KLab/autocommit_on
Support keyword argument to initially autocommit=on
2 parents 39406ea + f064692 commit c8b2744

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

MySQLdb/connections.py

+30-2
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,11 @@ class object, used to create cursors (keyword only)
139139
local_infile
140140
integer, non-zero enables LOAD LOCAL INFILE; zero disables
141141
142+
autocommit
143+
If False (default), autocommit is disabled.
144+
If True, autocommit is enabled.
145+
If None, autocommit isn't set and server default is used.
146+
142147
There are a number of undocumented, non-standard methods. See the
143148
documentation for the MySQL C API for some hints on what they do.
144149
@@ -182,6 +187,9 @@ class object, used to create cursors (keyword only)
182187

183188
kwargs2['client_flag'] = client_flag
184189

190+
# PEP-249 requires autocommit to be initially off
191+
autocommit = kwargs2.pop('autocommit', False)
192+
185193
super(Connection, self).__init__(*args, **kwargs2)
186194
self.cursorclass = cursorclass
187195
self.encoders = dict([ (k, v) for k, v in conv.items()
@@ -224,11 +232,29 @@ def string_decoder(s):
224232
self.encoders[types.StringType] = string_literal
225233
self.encoders[types.UnicodeType] = unicode_literal
226234
self._transactional = self.server_capabilities & CLIENT.TRANSACTIONS
235+
self._autocommit = None
227236
if self._transactional:
228-
# PEP-249 requires autocommit to be initially off
229-
self.autocommit(False)
237+
if autocommit is not None:
238+
self.autocommit(autocommit)
230239
self.messages = []
231240

241+
def autocommit(self, on):
242+
on = bool(on)
243+
_mysql.connection.autocommit(self, on)
244+
self._autocommit = on
245+
246+
def get_autocommit(self):
247+
if self._autocommit is None:
248+
self._update_autocommit()
249+
return self._autocommit
250+
251+
def _update_autocommit(self):
252+
cursor = cursors.Cursor(self)
253+
cursor.execute("SELECT @@AUTOCOMMIT")
254+
row = cursor.fetchone()
255+
self._autocommit = bool(row[0])
256+
cursor.close()
257+
232258
def cursor(self, cursorclass=None):
233259
"""
234260
@@ -241,6 +267,8 @@ def cursor(self, cursorclass=None):
241267
return (cursorclass or self.cursorclass)(self)
242268

243269
def __enter__(self):
270+
if self.get_autocommit():
271+
self.query("BEGIN")
244272
return self.cursor()
245273

246274
def __exit__(self, exc, value, tb):

0 commit comments

Comments
 (0)