Skip to content

Instantly share code, notes, and snippets.

@holmesconan
Created April 29, 2019 09:13
Show Gist options
  • Save holmesconan/2b3527b9e33452cf6cc6d3a011d3bad7 to your computer and use it in GitHub Desktop.
Save holmesconan/2b3527b9e33452cf6cc6d3a011d3bad7 to your computer and use it in GitHub Desktop.
pymysql skeleton
import pymysql.cursors
def execute(cursor):
# Read a single record
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('webmaster@python.org',))
result = cursor.fetchone()
print(result)
# Connect to the database
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
execute(cursor)
finally:
connection.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment