Last active
May 11, 2020 06:03
-
-
Save seozed/43895c0fec9edc6cce0d883cd5258236 to your computer and use it in GitHub Desktop.
[Database connect in python] #mysql #python
This file contains hidden or 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 | |
# 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, ('[email protected]', '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, ('[email protected]',)) | |
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