数据库学习——03—Mysql与Python交互(创建表、连接、关闭数据库等)

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

# -*- encoding: utf-8 -*-

'''
pip install pymysql    安装python的操作数据库

利用python对mysql进行增删改查的步骤

1、创建connection

2、获取connect

3、获取cursor的对象

4、关闭cursor

5、关闭connect

6、结束
'''
# 导包的方式
#import pymysql
#pymysql.connect()

# 另一种  连接方式   获取connect
from pymysql import *
# host='127.0.0.1'也可以,代表都是本机   port=3306代表端口号    database='python_01'数据库名称   账号密码:user='root', password='root' charset='utf8'字符集编码
conn = connect(host='localhost', port=3306, database='python_01', user='root', password='root', charset='utf8')

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

'''
# 获取cursor    第三步
cursor = conn.cursor()

print(cursor.execute('select * from students'))  # 执行sql的语句select * from students,   返回的是受影响的数据的行数

#result = cursor.fetchall()    # 传所有数据
#result = cursor.fetchone()    # 传一个数据
result = cursor.fetchmany(2)   # 传多个数据
print(result) # 元祖类型

# 第四步
cursor.close()   # 先关闭游标再关闭连接
conn.close()     # 连接关闭
# print("-"*50)

# 第五步
res = cursor.fetchmany(3)
print(res)                          # 这里数据能够输出是因为有缓存,正常情况下无法显示数据,因为和数据库的连接已经关闭了



对象的方法

  • close()关闭 先关闭游标,在关闭链接
  • execute(operation [, parameters ])执行语句,返回受影响的行数,主要用于执行insert、update、delete语句,也可以执行create、alter、drop等语句
  • fetchone()执行查询语句时,获取查询结果集的第一个行数据,返回一个元组
  • fetchall()执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回
# -*- encoding: utf-8 -*-
"""
@File    : python3_pymysql_demo1.py
@Time    : 2019/10/12 16:03
@Author  : chen

"""
from pymysql import *


class MyDb(object):
    def __init__(self):
        self.conn()
    
    # 数据库的连接
    def conn(self):
        try:
            self.conn=connect(
                host='localhost',
                port=3306,
                user='root',
                password='root',
                charset='utf8',
                db='python_01'
                
            )
        except Exception as e:         # 异常处理
            print(e)
            
    # 获取一条数据
    def get_one(self):
        sql = "select * from students"
        # 游标对象
        cursors = self.conn.cursor()
        cursors.execute(sql)
        result=cursors.fetchone()     # 获取一条数据
        # print(result)
        cursors.close()
        self.conn.close()
        return result
    
        '''
        sql = "select * from students"
        cursors=self.excute_sql(sql)    # 这部分就是减少的一部分重复代码
        result=cursors.fetchone()
        print(result)
        cursors.close()
        self.conn.close()
        return result
        '''
    
    # 获取更多数据
    def get_many(self):
        sql = "select * from students"
        # 游标对象
        cursors = self.conn.cursor()
        cursors.execute(sql)
        result = cursors.fetchall()          # 获取所有数据
        # print(result)
        cursors.close()
        # self.conn.close()
        self.close_conn()
        return result
    
    # 执行连接sql语句    即上面两个函数重复的连接数据库的语句,可以定义一个方法,减少代码量
    def excute_sql(self, sql):
        cursors = self.conn.cursor()
        cursors.execute(sql)
        return cursors
    
    # 新增  修改  删除   数据库讯息
    def operation(self):
        try:
            # # 新增数据sql实现
            # sql= 'insert into students(`name`) values(`老王`)'     # 注意符号是``   不是单引号''          # 新增
            # cursors =self.conn.cursor()
            # cursors.execute(sql)
            #
            # sql = 'insert into students(`name1`) values(`老王1`)'  # 注意符号是``   不是单引号''          # 新增
            # cursors = self.conn.cursor()
            # cursors.execute(sql)
            #
            # # 提交事务            当上main的sql语句没有出现问题的时候,可以一起执行提交sql语句,数据库也会改变,当语句中有一个错误时候,所有的sql都无法提交执行
            # self.conn.commit()
        
        
            # sql的更新操作
            sql = 'update students set name = `老王` where id =12'
            cursors.execute(sql)
            # 提交事务
            self.conn.commit()
            
            # 删除操作
            # sql = 'delete from students where id = 16'
            cursors.execute(sql)
            # 提交事务
            self.conn.commit()
            
        
        except Exception as e:
            print(e)
            
            # 部分提交        使用try : except 语句可以使多个sql语句中正确的部分进行提交执行    银行转账的情况下,不能使用部分提交,需要采用回滚
            # self.conn.commit()
            
            # 回滚                      即其中一条语句出现错误,所有的都不执行
            self.conn.rollback()
    
    
        
    def close_conn(self):
        try:
            self.conn.close()
        except Exception as e:
            print(e)
            
        
        
# 主函数就定义在main函数中
def main():
    obj = MyDb()
    # obj.get_one()    # 需要输出数据到对象中,否则报错pymysql.err.InterfaceError
   
    # res = obj.get_many()
    #
    # for item in res:
    #     print(item)
    
    obj.operation()         # 每次只执行一个sql的方法,否则报错pymysql.err.InterfaceError
    
    
    
if __name__ == '__main__':
    main()

代码实现商品查询功能函数

# -*- encoding: utf-8 -*-
"""
@File    : python3_pymysql_demo2.py
@Time    : 2019/10/12 16:52
@Author  : chen

"""
'''
1: 查询所有的商品
2: 查询商品的分类
3: 查询输入的品牌
'''
from pymysql import *

class Tb(object):
    def __init__(self):
        self.conn = connect(
                host='localhost',
                port=3306,
                user='root',
                password='root',
                charset='utf8',
                db='python-01'
                
            )
        self.cursor = self.conn.cursor()    # 创建游标对象
    
    @staticmethod
    def print_menu():    # 静态方法,当函数中不需要传参数的时候,可以使用静态方法@staticmethod
        print("1: 查询所有的商品")
        print("2: 查询商品的分类")
        print("3: 查询输入的品牌")
        print("4: 退出")
        num = input("请输入数字:")
        print("*" * 50)
        return num
    
    def execute_sql(self, sql):          # 减少重复的代码
        if self.cursor.execute(sql):                  # self.cursor.execute(sql)是输出查询数据的行数,为了防止数据库查询不到输入的品牌信息但是也
            # 不显示信息
            for item in self.cursor.fetchall():
                print(item)
        else:
            print("未查询到结果!")
            
    def show_all_goods(self):            # 定义不同查询sql语句的方法
        sql = 'select * from goods'
        self.execute_sql(sql)
    
    def show_all_cate(self):            # 定义不同查询sql语句的方法
        sql = 'select cate_name from goods'
        self.execute_sql(sql)
    
    def show_brand(self, brand_name):              # 定义不同查询sql语句的方法
        sql = "select * from goods where brand_name = '{}'".format(brand_name)
        self.execute_sql(sql)
        
        
    def run(self):
        while True:
            num = self.print_menu()
            if num == '1':
                self.show_all_goods()
            elif num == '2':
                self.show_all_cate()
            elif num == "3":
                brand_name = input("请输入品牌名称:")
                self.show_brand(brand_name)
                
            elif num == "4":
                self.cursor.close()
                self.conn.close()
            else:
                print("输入有误!请重新输入")
                
    
        

def main():
    tb = Tb()
    tb.run()


if __name__ == '__main__':
    main()



发布了50 篇原创文章 · 获赞 9 · 访问量 2092

猜你喜欢

转载自blog.csdn.net/weixin_42118531/article/details/103423942