python与mysql交互
python与mysql交互,该代码主要是把sql语句提取出来了,便于扩展,适合新手看看
import pymysql dict_data = dict() def outer_0(choose_method): """将所有要执行的代码用装饰器封装""" def inner_0(fun): def wrapped_0(): conn = pymysql.connect( host='localhost', user='root', database='jing_dong', passwd='mysql', charset='utf8', port=3306 ) cur = conn.cursor() print('*' * 50) data, pa = fun() cur.execute(data, pa) for temp in cur.fetchall(): print(temp) conn.commit() cur.close() conn.close() return None dict_data[choose_method] = wrapped_0 return wrapped_0 return inner_0 @outer_0('1') def check_data(): return """ select * from goods; """, None @outer_0('2') def check_data(): return """ select * from goods_cate; """,None @outer_0('3') def check_data(): return """ select * from goods_band; """,None @outer_0('4') def update_data(): id = input('输入要查询的id:') return """ select * from goods where id=%s""", id @outer_0('5') def update_data(): # 未完成 id = input('输入要查询的名字:') return """ select * from goods where name='%%s%'""",id @outer_0('7') def del_data(): id = input('输入要删除商品的id:') return """delete from goods where id= %s""", id def print_hint(): """打印提示""" print('1:查询所有商品信息') print('2:查询所有商品的种类信息') print('3:查询所有商品的品牌信息') print('4:根据id查询商品信息') print('5:根据名字查询商品信息') print('6:添加商品一件商品') print('7:删除一件商品') print('0:退出') # check_data() if __name__ == '__main__': while True: print_hint() name = input("输入要执行的操作编号:") if name is '0': break try: dict_data[name]() except Exception as ret: print(ret) print('输入有误,请输入0~6之间的数字')