|
| 1 | +from databricks import sql |
| 2 | +import os |
| 3 | + |
| 4 | +with sql.connect( |
| 5 | + server_hostname=os.getenv("DATABRICKS_SERVER_HOSTNAME"), |
| 6 | + http_path=os.getenv("DATABRICKS_HTTP_PATH"), |
| 7 | + access_token=os.getenv("DATABRICKS_TOKEN"), |
| 8 | +) as connection: |
| 9 | + |
| 10 | + # Disable autocommit to use explicit transactions |
| 11 | + connection.autocommit = False |
| 12 | + |
| 13 | + with connection.cursor() as cursor: |
| 14 | + try: |
| 15 | + # Create tables for demonstration |
| 16 | + cursor.execute("CREATE TABLE IF NOT EXISTS accounts (id int, balance int)") |
| 17 | + cursor.execute( |
| 18 | + "CREATE TABLE IF NOT EXISTS transfers (from_id int, to_id int, amount int)" |
| 19 | + ) |
| 20 | + connection.commit() |
| 21 | + |
| 22 | + # Start a new transaction - transfer money between accounts |
| 23 | + cursor.execute("INSERT INTO accounts VALUES (1, 1000), (2, 500)") |
| 24 | + cursor.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1") |
| 25 | + cursor.execute("UPDATE accounts SET balance = balance + 100 WHERE id = 2") |
| 26 | + cursor.execute("INSERT INTO transfers VALUES (1, 2, 100)") |
| 27 | + |
| 28 | + # Commit the transaction - all changes succeed together |
| 29 | + connection.commit() |
| 30 | + print("Transaction committed successfully") |
| 31 | + |
| 32 | + # Verify the results |
| 33 | + cursor.execute("SELECT * FROM accounts ORDER BY id") |
| 34 | + print("Accounts:", cursor.fetchall()) |
| 35 | + |
| 36 | + cursor.execute("SELECT * FROM transfers") |
| 37 | + print("Transfers:", cursor.fetchall()) |
| 38 | + |
| 39 | + except Exception as e: |
| 40 | + # Roll back on error - all changes are discarded |
| 41 | + connection.rollback() |
| 42 | + print(f"Transaction rolled back due to error: {e}") |
| 43 | + raise |
| 44 | + |
| 45 | + finally: |
| 46 | + # Restore autocommit to default state |
| 47 | + connection.autocommit = True |
0 commit comments