Skip to content

Instantly share code, notes, and snippets.

@mrgcohen
Forked from simonrw/python_pymysql_notes.md
Created August 27, 2018 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrgcohen/d129ba6974729099d3ee7c6fa0a09403 to your computer and use it in GitHub Desktop.
Save mrgcohen/d129ba6974729099d3ee7c6fa0a09403 to your computer and use it in GitHub Desktop.
Notes about pymysql connections

Database transactions

pymysql

  • Defaults to autocommit=False
connection = pymysql.connect(user='user', db='test')
cursor = connection.cursor()
cursor.execute('insert into test (value) values (10)')
connection.close()

connection = pymysql.connect(user='user', db='test')
cursor = connection.cursor()
cursor.execute('select value from test')
# => []

To commit changes to the database, #commit() must be called:

connection = pymysql.connect(user='user', db='test')
cursor = connection.cursor()
cursor.execute('insert into test (value) values (10)')
# Call the commit line
connection.commit()
connection.close()

connection = pymysql.connect(user='user', db='test')
cursor = connection.cursor()
cursor.execute('select value from test')
# => [(10, )]

With a context manager on a connection, an implicit transaction is opened:

with pymysql.connect(user='user', db='test') as cursor:
    cursor.execute('insert into test (value) values (10)')

with pymysql.connect(user='user', db='test') as cursor:
    cursor.execute('select value from test')
    # => [(10, )]

The connect function includes an autocommit parameter:

connection = pymysql.connect(user='user', db='test', autocommit=True)
cursor = connection.cursor()
cursor.execute('insert into test (value) values (10)')
connection.close()

connection = pymysql.connect(user='user', db='test')
cursor = connection.cursor()
cursor.execute('select value from test')
# => [(10, )]

Multiple cursors can see any changes made within a transaction

connection = pymysql.connect(user='user', db='test')
cursor = connection.cursor()
cursor2 = connection.cursor()
cursor.execute('insert into test (value) values (10)')
cursor2.execute('select value from test')
# => [(10, )]

Multiple connections are isolated from each other

connection = pymysql.connect(user='user', db='test')
connection2 = pymysql.connect(user='user', db='test')
cursor = connection.cursor()
cursor2 = connection2.cursor()
cursor.execute('insert into test (value) values (10)')
cursor2.execute('select value from test')
# => []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment