Created
April 29, 2019 09:13
-
-
Save holmesconan/2b3527b9e33452cf6cc6d3a011d3bad7 to your computer and use it in GitHub Desktop.
pymysql skeleton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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