python使用SQL语句的类方法

该博客展示了使用Python的pymysql库操作MySQL数据库的代码。定义了一个JD类,包含数据库连接、执行SQL语句、查询商品信息、品牌信息、价格信息以及插入商品品牌等功能,通过用户输入的编码执行相应操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from pymysql import connect


class JD(object):
    def __init__(self):
        self.connect = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
        self.cursor=self.connect.cursor()

    def execute(self,sql):
        self.cursor.execute(sql)
        for i in self.cursor.fetchall():
            print(i)

    def all_goods(self):
        sql="select * from goods;"
        self.execute(sql)
        
    def all_price(self):
        sql="select name,price from goods;"
        self.execute(sql)
        
    def all_brands(self):
        sql="select * from goods_brands;"
        self.execute(sql)

    def insert(self):
        str = input("商品名称:")
        sql = "insert into goods_brands (name) values (%s);"
        self.cursor.execute(sql,[str])
        # self.cursor.execute("insert into goods_brands (name) values ('%s');"%str)
        self.connect.commit()

        

    def __del__(self):
        self.cursor.close()
        self.connect.close()

    def print_(self):
        print("查询的所有商品请按【1】、品牌请按【2】、价格请按【3】、添加商品【4】: ")
        a=input("请输入查询编码:")
        return a

    def run(self):
        while True:
            num = self.print_()
            if num=="1":
                self.all_goods()

            elif num=="2":
                self.all_brands()

            elif num=="3":
                self.all_price()
            elif num=="4":
                self.insert()

            else:
                break


def main():
    jd = JD()
    jd.run()
        
if __name__ == '__main__':
    main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值