importpymysqlclassMysql():defcreate(self):try:
sql_creat= """CREATE TABLE data_test(
id INT unique,
name VARCHAR(50),
age INT,
sex enum('男','女')
)"""cursor.execute(sql_creat)print("建表成功")exceptUserWarning:print("建表失败")definsert(self):try:
sql_insert= """insert into data_test(id, name, age, sex) VALUES(1, '李牧', 18, '男'),(2, '栗子', 20, '女'),(3, '测试', 26, '男'),(4, '尕娃', 30, '女')"""cursor.execute(sql_insert)print("插入数据成功")exceptUserWarning:print("插入数据失败")defselect(self):try:
sql_select= """select name from data_test where sex='男'"""cursor.execute(sql_select)print("查询数据成功")exceptUserWarning:print("插入数据失败")defdelete(self):try:
sql_delete= """delete from data_test where id=3"""cursor.execute(sql_delete)print("数据删除成功")exceptUserWarning:print("数据删除失败")defupdata(self):try:
sql_update= """update data_test set sex='男' where sex='女'"""cursor.execute(sql_update)print("数据更新成功")exceptUserWarning:print("数据更新失败")defdelete_table(self):
sql_delete_table= """drop table data_test"""cursor.execute(sql_delete_table)print("清洗数据:删除数据表")if __name__ == '__main__':
con= pymysql.connect("localhost", "root", "123456", "test04", charset='utf8')
cursor=con.cursor()#实例化
test =Mysql()#建一张学生表 包含(id,name,age,sex)
test.create()#增加四条数据
test.insert()
con.commit()#提交
#查询表中sex为男的数据
test.select()print(cursor.fetchall())#删除id =3的数据
test.delete()
con.commit()#提交
#将sex为女的,修改为男
test.updata()
con.commit()#提交
test.delete_table()
cursor.close()