Skip to content

Instantly share code, notes, and snippets.

@initialkommit
Created August 20, 2016 10:45
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 initialkommit/04057a120ae08834e651cc3bf8ca6aca to your computer and use it in GitHub Desktop.
Save initialkommit/04057a120ae08834e651cc3bf8ca6aca to your computer and use it in GitHub Desktop.
CRUD Practice to MySQL
import pymysql
def db_connection():
db = pymysql.connect("localhost", "root", "", "djangogirls") # host, user, password, db
return db
def select():
"""CRUD - Reading"""
db = db_connection()
cursor = db.cursor()
cursor.execute("select * from person")
data = cursor.fetchall()
for item in data:
print(item)
cursor.close()
db.close()
def insert():
"""CRUD - Creating"""
db = db_connection()
cursor = db.cursor()
_insert_value = {
'email': 'initialkommit@gmail.com',
'name': 'kwangyoun',
'gender': 'm'
}
sql = """INSERT INTO person (email, name, gender) values """
sql += """('{email}', '{name}', '{gender}')""".format(**_insert_value)
try:
cursor.execute(sql)
db.commit()
except pymysql.IntegrityError as e:
print(e)
db.rollback()
cursor.close()
db.close()
def update():
"""CRUD - Update"""
# do something
def delete():
"""CRUD - Delete"""
# do somethin
if __name__ == '__main__':
insert()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment