pymysql

面向对象思维python对接mysql数据库:

 1 from pymysql import *
 2 
 3 class JD(object):
 4 
 5     def __init__(self):
 6         # 获取connection连接
 7         self.conn = connect(host='localhost',port=3306,user='root',password='',database='jing_dong',charset='utf8')
 8         # 获取cursor对象
 9         self.cursor = self.conn.cursor()
10 
11     def __del__(self):
12         # 关闭cursor对象
13         self.cursor.close()
14         self.conn.close()
15 
16     def execute_sql(self,sql):
17         """根据需求查询数据"""
18         self.cursor.execute(sql)
19         for item in self.cursor.fetchall():
20             print(item)
21 
22     def show_all_items(self):
23         """显示所有商品"""
24         sql = 'select * from goods;'
25         self.execute_sql(sql)
26 
27     def show_cates(self):
28         """显示所有的商品分类"""
29         sql = 'select name from goods_cates;'
30         self.execute_sql(sql)
31 
32     def show_brands(self):
33         """显示所有的商品品牌分类"""
34         sql = 'select name from goods_brands;'
35         self.execute_sql(sql)
36 
37     def add_brands(self):
38         """添加品牌分类"""
39         item_name = input("输入新的品牌的名称:")
40         try:
41             sql = "insert into goods_brands (name) values('%s');" % item_name
42             self.cursor.execute(sql)
43         except:
44             self.conn.rollback()
45         self.conn.commit()
46 
47     def get_info_by_name(self):
48         find_name = input("请输入查询的商品名:")
49         # sql = 'select * from goods where name="%s"' % find_name
50         # self.execute_sql(sql)
51         # sql语句的参数化,可以有效防止sql注入
52         sql = 'select * from goods where name=%s;'
53         self.cursor.execute(sql, [find_name])
54         print(self.cursor.fetchall())
55 
56     def print_menu(self):
57         """程序启动页面"""
58         print("-----京东商城-----")
59         print("1.显示所有的商品")
60         print("2.显示所有的商品分类")
61         print("3.显示所有的商品品牌分类")
62         print("4.添加品牌分类")
63         print("5.根据名字查询一个商品")
64         return input("请输入功能对应的序号:")
65 
66     def run(self):
67         while True:
68             num = self.print_menu()
69             if num == "1":
70                 # 查询所有商品
71                 self.show_all_items()
72             elif num == "2":
73                 # 查询所有商品分类
74                 self.show_cates()
75             elif num == "3":
76                 # 查询素有商品品牌分类
77                 self.show_brands()
78             elif num == "4":
79                 # 添加品牌分类
80                 self.add_brands()
81             elif num == "5":
82                 self.get_info_by_name()
83             else:
84                 print("请输入有效的数字!")
85 
86 
87 def main():
88     # 1.创建一个京东商城对象
89     jd = JD()
90 
91     # 2.调用这个对象的run方法,让其运行
92     jd.run()
93 
94 
95 if __name__ == '__main__':
96     main()
97     
原文地址:https://www.cnblogs.com/zzmx0/p/12741546.html