python进阶(十一)_使用python链接MySQL

1.Python 中操作 MySQL 步骤在这里插入图片描述

2.引入模块

在py文件中引入pymysql模块

from pymysql import *`
Connection 对象
  • 用于建立与数据库的连接
  • 创建对象:调用connect()方法

conn=connect(参数列表)
参数host:连接的mysql主机,如果本机是’localhost’
参数port:连接的mysql主机的端口,默认是3306
参数database:数据库的名称
参数user:连接的用户名
参数password:连接的密码
参数charset:通信采用的编码方式,推荐使用utf8

  • 对象的方法

close()关闭连接
commit()提交
cursor()返回Cursor对象,用于执行sql语句并获得结果

Cursor对象
  • 用于执行sql语句,使用频度最高的语句为select、insert、update、delete
  • 获取Cursor对象:调用Connection对象的cursor()方法
cs1=conn.cursor()
  • 对象的方法
    • close()关闭
    • execute(operation [, parameters ])执行语句,返回受影响的行数,主要用于执行insert、update、delete语句,也可以执行create、alter、drop等语句
    • etchone()执行查询语句时,获取查询结果集的第一个行数据,返回一个元组
    • fetchall()执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回
  • 对象的属性
    • rowcount只读属性,表示最近一次execute()执行后受影响的行数
    • connection获得当前连接对象
实例程序
from pymysql import *

class JD(object):
    """docstring for DJ"""
    def __init__(self):
        # 创建Connection连接
        self.conn = connect(host='localhost',port=3306,database='jing_dong',user='root',password='824750',charset='utf8')
        # 获得Cursor对象
        self.cursor = self.conn.cursor()

    def __def__(self):
        # 关闭Cursor对象
        self.cursor.close()
        # 关闭Connection对象
        slef.conn.close()

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

    def show_all_items(self):
        """显示所有商品"""
        sql = "select * from goods;"
        self.execute_sql(sql)

    def show_cates(self):
        sql = "select name from goods_cates;"
        self.execute_sql(sql)

    def show_brands(self):
        sql = "select name from goods_brands;"
        self.execute_sql(sql)

    def add_brands(self):
        item_name = input("输入新商品分类的名称:")
        sql = """insert into goods_brands (name) values("%s")""" % item_name
        self.cursor.execute(sql,[find_name])
        self.conn.commit()

    def get_info_by_name(self):
        find_name = input("请输入要查询的商品名字:")
        sql = " select * from goods where name=%s"
        self.cursor.execute(sql,[find_name])
        print(self.cursor.fetchall())

    @staticmethod
    def print_menu():
        print("-----京东-----")
        print("1:所有的商品")
        print("2:所有的商品分类")
        print("3:所有的商品品牌的分类")
        print("4:添加商品分类")
        print("5:根据名字查询一个商品")
        return input("请输入功能对应的序号:")

    def run(self):
        while True:
            num = self.print_menu()

            if num == "1":
                # 查询所有商品
                self.show_all_items()
            elif num == "2" :
                # 查询所有商品的分类
                self.show_cates()
            elif num == "3" :
                # 查询所有的商品品牌的分类
                self.show_brands()
            elif num == "4" :
                # 添加品牌的分类
                self.add_brands()
            elif num == "5" :
                # 根据名字查询一个商品
                self.get_info_by_name()
            else:
                print("输入有误,重新输入")


def main():
    jd = JD()

    jd.run()


if __name__ == '__main__':
    main()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值