In [2]:
!pip install PyMySQL pandas
In [1]:
# %load util.py
from IPython.display import display
import pandas as pd
import pymysql.cursors
from collections import defaultdict
def print_table():
db_result = []
try:
connection = get_connection()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT * FROM `auth_user` "
cursor.execute(sql)
db_result = cursor.fetchall()
finally:
connection.close()
if not db_result:
return
if isinstance(db_result, dict):
db_result = [db_result]
data = defaultdict(list)
for item in db_result:
for key in item:
data[key].append(item[key])
df = pd.DataFrame(data)
display(df)
def get_connection():
connection = pymysql.connect(host='192.168.0.88',
user='root',
password='letmegoletmego',
db='db',
port=32768,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
return connection
def reset_table():
connection = get_connection()
table_sql = '''
DROP TABLE IF EXISTS `auth_user`;
CREATE TABLE `auth_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`password` varchar(128) NOT NULL,
`last_login` datetime DEFAULT NULL,
`is_superuser` tinyint(1) NOT NULL,
`username` varchar(150) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
'''
try:
with connection.cursor() as cursor:
cursor.execute(table_sql)
finally:
connection.close()
In [8]:
reset_table() # 重置表(删除,创建)
In [9]:
try:
connection = get_connection()
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `auth_user` (`username`, `password`,`is_superuser`,`last_login`) VALUES (%s, %s,%s,%s)"
# cursor.execute(sql, ('郭靖', '66666',1,'2017-6-21'))
# cursor.execute(sql, ('黄蓉', '77777',0,'2017-6-22'))
# cursor.execute(sql, ('郭襄', '88888',1,'2017-6-25'))
cursor.executemany(sql, [('郭靖', '66666',1,'2017-6-21'),('黄蓉', '77777',0,'2017-6-22'),('郭襄', '88888',1,'2017-6-25')])
connection.commit()
finally:
connection.close()
print_table()
In [32]:
try:
connection = get_connection()
with connection.cursor() as cursor:
# Create a new record
sql = "UPDATE `auth_user` SET password = %s WHERE username = %s"
cursor.execute(sql, ( '66666_XXX','郭靖'))
cursor.execute(sql, ('77777_XXX','黄蓉'))
cursor.execute(sql, ( '88888_XXX','郭襄'))
connection.commit()
finally:
connection.close()
print_table()
In [33]:
try:
connection = get_connection()
with connection.cursor() as cursor:
# Create a new record
sql = "DELETE from `auth_user` WHERE username = %s"
cursor.execute(sql, ( '郭靖'))
connection.commit()
finally:
connection.close()
print_table()
In [44]:
try:
reset_table()
connection = get_connection()
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `auth_user` (`username`, `password`,`is_superuser`,`last_login`) VALUES (%s, %s,%s,%s)"
cursor.execute(sql, ('郭靖', '66666',1,'2017-6-21'))
cursor.execute(sql, ('黄蓉', '77777','xxx','2017-6-22'))
cursor.execute(sql, ('郭襄', '88888',1,'2017-6-25'))
connection.commit()
except Exception as e:
print(e)
#connection.rollback()
finally:
connection.commit()
connection.close()
print_table()
首先说明一下, 当执行 commit 或 ROLLBACK后,放在回滚段中的数据就会被删除.
connection.rollback()
,则最后结果为空.