Python操作MySQL数据库
1 from pymysql import connect 2 3 4 # ------------------------------------------------------------ 5 # -------------Python操作MySQL数据库,进行正删改查---------------- 6 # ------------------------------------------------------------ 7 class Goods(object): 8 def __init__(self): 9 # 创建Connection连接 10 self.conn = connect(host='localhost', port=3306, user='root', 11 password='spring123', database='test', 12 charset='utf8') 13 # 获得Cursor对象 14 self.cursor = self.conn.cursor() 15 16 def __del__(self): 17 # 关闭Cursor对象 18 self.cursor.close() 19 self.conn.close() 20 21 def show_all_question(self): 22 sql = "select * from question" 23 self.excute_sql(sql) 24 25 def show_all_user(self): 26 sql = "select * from user" 27 self.excute_sql(sql) 28 29 def excute_sql(self, sql): 30 self.cursor.execute(sql) 31 for temp in self.cursor.fetchall(): 32 print(temp) 33 34 def get_info_by_name(self): 35 find_name = input("请输入您要查询的用户姓名:") 36 sql = " select * from user where name =%s" 37 self.cursor.execute(sql, [find_name]) 38 print(self.cursor.fetchall()) 39 40 def excute_many_data(self, sql, vals): 41 self.cursor.executemany(sql, vals) 42 self.conn.commit() 43 44 def add_user(self): 45 name = input("请输入姓名:") 46 age = input("请输入年龄:") 47 sex = input("请输入性别:") 48 hobby = input("请输入爱好:") 49 address = input("请输入地址:") 50 cardId = input("请输入身份证:") 51 segment = input("请输入段位:") 52 sql = "insert into user (name,age,sex,hobby,address,cardId,segment) values ('%s','%s','%s','%s','%s','%s','%s')" % ( 53 name, age, sex, hobby, address, cardId, segment) 54 self.cursor.execute(sql) 55 self.conn.commit() 56 57 @staticmethod 58 def print_menu(): 59 print("---------打印信息---------") 60 return input("请输入功能对应的序号:") 61 62 def run(self): 63 while True: 64 num = self.print_menu() 65 if num == "1": 66 # 查询用户信息 67 self.show_all_user() 68 elif num == "2": 69 # 查询试题信息 70 self.show_all_question() 71 elif num == "3": 72 self.add_user() 73 elif num == "4": 74 self.get_info_by_name() 75 else: 76 print("输入有误,重新输入...") 77 78 79 def main(): 80 g = Goods() 81 g.run() 82 83 84 if __name__ == '__main__': 85 main()