You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+2-27Lines changed: 2 additions & 27 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -69,34 +69,9 @@ or to a Databricks Runtime interactive cluster (e.g. /sql/protocolv1/o/123456789
69
69
70
70
## Transaction Support
71
71
72
-
The connector supports multi-statement transactions with manual commit/rollback control:
72
+
The connector supports multi-statement transactions with manual commit/rollback control. Set `connection.autocommit = False` to disable autocommit mode, then use `connection.commit()` and `connection.rollback()` to control transactions.
73
73
74
-
```python
75
-
import os
76
-
from databricks import sql
77
-
78
-
connection = sql.connect(
79
-
server_hostname=os.getenv("DATABRICKS_HOST"),
80
-
http_path=os.getenv("DATABRICKS_HTTP_PATH")
81
-
)
82
-
83
-
# Disable autocommit to use explicit transactions
84
-
connection.autocommit =False
85
-
86
-
cursor = connection.cursor()
87
-
try:
88
-
cursor.execute("INSERT INTO table1 VALUES (1, 'a')")
89
-
cursor.execute("INSERT INTO table2 VALUES (2, 'b')")
90
-
connection.commit() # Commit both inserts atomically
91
-
exceptExceptionas e:
92
-
connection.rollback() # Rollback on error
93
-
raise
94
-
95
-
cursor.close()
96
-
connection.close()
97
-
```
98
-
99
-
For detailed information about transaction behavior, isolation levels, error handling, and best practices, see [TRANSACTIONS.md](TRANSACTIONS.md).
74
+
For detailed documentation, examples, and best practices, see **[TRANSACTIONS.md](TRANSACTIONS.md)**.
100
75
101
76
## SQLAlchemy
102
77
Starting from `databricks-sql-connector` version 4.0.0 SQLAlchemy support has been extracted to a new library `databricks-sqlalchemy`.
Copy file name to clipboardExpand all lines: TRANSACTIONS.md
+30-11Lines changed: 30 additions & 11 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -53,6 +53,8 @@ try:
53
53
exceptExceptionas e:
54
54
connection.rollback() # Neither insert is saved
55
55
raise
56
+
finally:
57
+
connection.autocommit =True# Restore default state
56
58
```
57
59
58
60
### Rolling Back Changes
@@ -106,6 +108,8 @@ try:
106
108
exceptExceptionas e:
107
109
connection.rollback() # All three inserts are discarded
108
110
raise
111
+
finally:
112
+
connection.autocommit =True# Restore default state
109
113
```
110
114
111
115
This is particularly useful for maintaining data consistency across related tables.
@@ -175,14 +179,19 @@ You cannot change autocommit mode while a transaction is active:
175
179
176
180
```python
177
181
connection.autocommit =False
178
-
cursor.execute("INSERT INTO logs VALUES (1, 'data')")
182
+
cursor= connection.cursor()
179
183
180
-
# This will raise TransactionError
181
184
try:
182
-
connection.autocommit =True
185
+
cursor.execute("INSERT INTO logs VALUES (1, 'data')")
186
+
187
+
# This will raise TransactionError
188
+
connection.autocommit =True# Error: transaction is active
189
+
183
190
except sql.TransactionError as e:
184
191
print(f"Cannot change autocommit: {e}")
185
-
connection.rollback() # Clean up
192
+
connection.rollback() # Clean up the transaction
193
+
finally:
194
+
connection.autocommit =True# Now it's safe to restore
186
195
```
187
196
188
197
### Committing Without an Active Transaction
@@ -215,14 +224,19 @@ try:
215
224
exceptExceptionas e:
216
225
connection.rollback() # Discard the partial transaction
217
226
218
-
# Now you can start a fresh transaction
219
-
cursor.execute("INSERT INTO error_log VALUES (1, 'Query failed')")
220
-
connection.commit()
227
+
# Log the error (with autocommit still disabled)
228
+
try:
229
+
cursor.execute("INSERT INTO error_log VALUES (1, 'Query failed')")
230
+
connection.commit()
231
+
exceptException:
232
+
connection.rollback()
233
+
finally:
234
+
connection.autocommit =True# Restore default state
221
235
```
222
236
223
237
## Querying Server State
224
238
225
-
By default, the `autocommit` property returns a cached value for performance. If you need to query the server each time (for example, if you're debugging or the state might change externally):
239
+
By default, the `autocommit` property returns a cached value for performance. If you need to query the server each time (for instance, when strong consistency is required):
226
240
227
241
```python
228
242
connection = sql.connect(
@@ -291,7 +305,7 @@ conn2.commit() # Also OK
291
305
292
306
1.**Keep transactions short**: Long-running transactions can cause conflicts with other connections. Commit as soon as your atomic unit of work is complete.
293
307
294
-
2.**Always handle exceptions**: Wrap transaction code in try/except and call `rollback()` on errors.
308
+
2.**Always handle exceptions**: Wrap transaction code in try/except/finally and call `rollback()` on errors.
295
309
296
310
```python
297
311
connection.autocommit =False
@@ -305,6 +319,8 @@ except Exception as e:
305
319
connection.rollback()
306
320
logger.error(f"Transaction failed: {e}")
307
321
raise
322
+
finally:
323
+
connection.autocommit =True# Restore default state
308
324
```
309
325
310
326
3.**Use context managers**: If you're writing helper functions, consider using a context manager pattern:
@@ -331,15 +347,18 @@ with transaction(connection):
331
347
# Auto-commits on success, auto-rolls back on exception
332
348
```
333
349
334
-
4.**Reset autocommit when done**: After using explicit transactions, consider resetting autocommit to True for subsequent operations:
350
+
4.**Reset autocommit when done**: Use a `finally` block to restore autocommit to `True`. This is especially important if the connection is reused or part of a connection pool:
335
351
336
352
```python
337
353
connection.autocommit =False
338
354
try:
339
355
# ... transaction code ...
340
356
connection.commit()
357
+
exceptException:
358
+
connection.rollback()
359
+
raise
341
360
finally:
342
-
connection.autocommit =True#Reset to default
361
+
connection.autocommit =True#Restore to default state
343
362
```
344
363
345
364
5.**Be aware of isolation semantics**: Remember that repeatable read means you see a snapshot from the start of your transaction. If you need to see recent changes from other transactions, commit your current transaction and start a new one.
0 commit comments