学习Python第16天_通过Python操作数据库

仅记录个人学习Python所学,学识浅薄,若有错误欢迎指出。文章可能会不太完善,后续可能会继续更新。
这里的数据库就不重复建了,代码直接跑应该会报错。

一、连接MySQL
import pymysql
# pymysql包 需要进行安装

# 连接MySQL
# 1.连接mysql
# 2.操作数据库
# 3.断开连接

# 1.连接mysql
# conn = pymysql.connect(host='', user='', password='', database='')
# host 连接地址,可以是localhost / 127.0.0.1 自己的主机
# user 为用户名 是在安装mysql时的用户名,password 是安装数据库时的密码,database 是要操作的数据库
# 如果端口号不是默认 3306的 需要在连接语句中 加入端口号 port 这里的charset 是设置字符集,默认是utf8的可以不进行设置
conn = pymysql.connect('', '', '', '', charset='utf8')

# 2.创建游标:执行sql语句
cursor = conn.cursor()

# 3.执行SQL
sql = 'select * from user'
cursor.execute(sql)  # 执行SQL

# 4.获取查询结果
res = cursor.fetchall()	 # fetchall() 为输出所有结果
print(res)

# 5.关闭连接
cursor.close()	# 这里需要先关闭游标
conn.close()	# 再关闭数据库连接
二、增删改
import pymysql
import random

# 增删改

db = pymysql.connect('localhost', 'root', '123456', 'mydb')

with db.cursor() as cursor:
    # 插入数据
    # 插入一条数据	插入过的就不要重复插入了,否则因为主键冲突会报错
    # cursor.execute('insert into user(name,age) values("王五",30)')

    # 插入多条数据
    # for i in range(11, 21):
    #     name = str("赵"+str(i))
    #     age = random.randint(20, 100)
    #     # cursor.execute(f'insert into user(name,age) values("{name}",{age})')
    #     cursor.execute('insert into user(name,age) values("%s",%d)' % (name, age))

    # 删除数据
    # cursor.execute('delete from user where name like "赵%"')

    # 更新数据
    # cursor.execute('update user set age=20 where id=5')

    # 异常处理
    try:
        cursor.execute('update user2 set age=20 where id=5')
        db.commit()  # 提交
    except Exception as e:	# 这里最好是捕获下异常,如果有错误可以知道具体是什么错误
        print(e)  # (1146, "Table 'mydb.user2' doesn't exist")
        db.rollback()  # 回滚

db.close()

commit()进行事物的提交,也可以在连接的时候把 autocommit属性的值改为True (自动提交)
rollback()进行回滚,一般配合 try except 使用,出现错误时,撤销操作语句
增删改 对数据库有更改的 操作一般都需要commit()rollback()

import pymysql
from pymysql.cursors import DictCursor

# 查

conn = pymysql.connect('localhost', 'root', '123456', 'mydb')

with conn.cursor('''cursor=DictCursor''') as cursor:
    # 执行查询的SQL语句
    cursor.execute('select * from user')
    # 获取查询结果
    # res = cursor.fetchall()  # 获取所有数据

    # res = cursor.fetchone()  # 获取下一个数据

    res = cursor.fetchmany(3)  # 获取多条数据
    print(res)
    # 使用DictCursor得到
    '''[{'id': 1, 'name': '张三', 'age': 23}, {'id': 2, 'name': '李四', 'age': 88}, {'id': 5, 'name': '陈十一', 'age': 20}]'''

conn.close()

这里补充一下分页查询的代码

# 查: 分页查询员工信息
    def get_emp(self, page=1, per_page=5):
        '''

        :param page: 页码
        :param per_page: 每页数量
        :return: 某页的员工数据
        '''
        try:
            with self.db.cursor(cursor=DictCursor) as cursor:
                cursor.execute('select * from tb_emp limit %s,%s', ((page - 1) * per_page, per_page))
                return cursor.fetchall()
        except Exception as e:
            print('查询失败', e)

可以创建一个通用的类,方便 如果需要用到Python进行数据库操作,将方法都封装起来,便于使用

class SQL:
	# 连接数据库
    def __init__(self, host='localhost', user='root', password='', database='', port=3306):
        self.db = pymysql.connect(
            host=host, port=port, user=user, password=password, database=database, autocommit=True)
            
	# 关闭MySQL连接
    def close(self):
        self.db.close()
        
	# 封装的修改方法:增删改操作
    def __edit(self, sql):
        count = 0
        try:
            with self.db.cursor() as cursor:
                count = cursor.execute(sql)
        except Exception as e:
            print('操作失败', e)
            self.db.rollback()
        return count        

之后可以分别定义方法进行调用
对表进行分页查询

    def get_page(self, table_name, page=1, per_page=5):
        '''

        :param table_name: 要查询的表名
        :param page: 页码
        :param per_page: 每页数量
        :return: 某页的员工数据
        '''
        try:
            with self.conn.cursor(cursor=DictCursor) as cursor:
                cursor.execute(f'select * from {table_name} limit {(page - 1) * per_page},{per_page}')
                return cursor.fetchall()
        except Exception as e:
            print('查询错误', e)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值