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("輸入條件錯誤!")