Skip to content

Instantly share code, notes, and snippets.

@seozed
Last active May 11, 2020 06:03
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 seozed/43895c0fec9edc6cce0d883cd5258236 to your computer and use it in GitHub Desktop.
Save seozed/43895c0fec9edc6cce0d883cd5258236 to your computer and use it in GitHub Desktop.
[Database connect in python] #mysql #python
import pymysql.cursors
# 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:
# Read a single record
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('webmaster@python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment