Python与MySQL的基本流程
# 导入模块from pymysql import *# 链接数据库conn = connect(host = "localhost",port = 3306,user=‘root‘,password="135853",database="jing_dong",charset="utf8")# 获取有标对象cursor = conn.cursor()# 通过execute执行sql语句cursor.execute("select * from goods;")print(cursor.fetchall())
# 输出表一条数据
print(cursor.fetchone())
# 输出表所有数据print(cursor.fetchall())# 输出表指定数据print(cursor.fetchmany(6))# 关闭对象conn.close()cursor.close()
mysql与Python的交互
首先先建立一个jing_dong数据库,再来一个goods 和 goods_cates表
开始交互
from pymysql import *class Jd: def __init__(self): # 1.链接数据库 self.conn = connect(host = "localhost",port = 3306,user=‘root‘,password="135853",database="jing_dong",charset="utf8") # 创建油标 self.curs = self.conn.cursor() def __del__(self): # 关闭链接 self.conn.close() self.curs.close() def execuets(self,sql): # 执行MySQL的语句 self.curs.execute(sql) # 遍历接受到的数据 for i in self.curs.fetchall(): print(i) def cxsy(self): """查询所有商品""" sql = "select * from goods;" self.execuets(sql) def spfe(self): sql = "select name from goods_cates;" self.execuets(sql) def ppfl(self): sql = "select brand_name from goods group by brand_name;" self.execuets(sql) def jiemain(self): print("-----京东------") print("1:所有商品") print("2:所有商品分类") print("3:所有商品品牌分类") return input("请输入对应的功能序号:") def run(self): while True: nus = self.jiemain() if nus == "1": #查询所有商品 self.cxsy() elif nus == "2": #查询所有的商品分类 self.spfe() elif nus == "3": #查询所有的商品品牌分类 self.ppfl() else: print("输入错误,请重新输入!!!")def main(): jd = Jd() jd.run()if __name__ == ‘__main__‘: main()