import pymysql.cursors
import datetime
class Experiment5:
def __init__(self):
self.connect = pymysql.Connect(
host='localhost',
port=3306,
user='root',
passwd='',
db='TT',
charset='utf8'
)
self.cursor = self.connect.cursor()
def delete(self):
try:
try:
id = int(input("请输入要删除的id序号:"))
except:
print("输入非法")
return
sql = "delete from student where sno=%d" % id
print(sql)
self.cursor.execute(sql)
self.connect.commit()
print('成功删除', self.cursor.rowcount, '条数据')
except Exception as e:
# print(str(e))
print("不存在该数据")
def add(self):
try:
sql = "INSERT INTO student (sname, sex, sage) VALUES ('%s','%s','%s' )"
sname = input("名字:")
sex = input("性别:")
sage = input("年龄:")
data = (sname, sex, sage)
self.cursor.execute(sql % data)
self.connect.commit()
print('成功插入', self.cursor.rowcount, '条数据')
print()
except:
print("存在约束条件!无法插入!")
def update(self):
self.showAll()
try:
try:
id = int(input("请输入要修改的id序号:"))
except:
print("输入非法")
return
sql = "update student set sname='%s',sage=%d,sex='%s' where sno=%d"
sname = input("名字:")
sex = input("性别:")
try:
sage = int(input("年龄:"))
except:
print("输入非法")
return
data = (sname, sage, sex, id)
self.cursor.execute(sql % data)
self.connect.commit()
print('成功修改', self.cursor.rowcount, '条数据')
except Exception as e:
# print(str(e))
print("修改失败!")
def showAll(self):
try:
sql = "select * from student"
self.cursor.execute(sql)
self.connect.commit()
for row in self.cursor.fetchall():
print("编号:%d\t学生姓名:%s\t年龄:%d\t性别:%s" % row)
print('共查找出', self.cursor.rowcount, '条数据')
print()
except Exception as e:
# print(str(e))
print("不存在该数据!")
def query(self):
try:
query = input("查询条件:(姓名='1');(年龄>1);(性别='男')")
query=query.replace("姓名","sname")
query=query.replace("年龄","sage")
query=query.replace("性别","sex")
queries = query.split(";")
query = " and ".join(queries)
sql = "select * from student where "+query
print(sql)
self.cursor.execute(sql)
self.connect.commit()
for row in self.cursor.fetchall():
print("编号:%d\t学生姓名:%s\t年龄:%d\t性别:%s" % row)
print('共查找出', self.cursor.rowcount, '条数据')
print()
except Exception as e:
print(str(e))
print("输入条件错误!")