您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

MySQL与Python的交互

bubuko 2022/1/25 20:08:44 mysql 字数 9534 阅读 797 来源 http://www.bubuko.com/infolist-5-1.html

Python与MySQL的基本流程 # 导入模块 from pymysql import * # 链接数据库 conn = connect(host = "localhost",port = 3306,user='root',password="135853",database="jing_dong ...

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()

 

MySQL与Python的交互

原文:https://www.cnblogs.com/wocaonidaye/p/12397699.html


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶