Python程序接入MySQL数据库

该博客演示了Python如何连接并操作MySQL数据库,包括删除、更新、查询和插入数据。示例中展示了使用pymysql库进行数据库交互,涉及游标对象、事务处理和数据处理方法。同时,还展示了批量插入数据的高效方法,避免一次性加载大量数据导致内存问题。
摘要由CSDN通过智能技术生成

Python程序接入MySQL数据库

删除数据

"""
example02 - 输入部门编号,删除对应的部门
        - 删除数据

Author: Hao
Date: 2021/8/31
"""
import pymysql

no = int(input('要删除的部门编号: '))
conn = pymysql.connect(host='47.104.31.138', port=3306,
                       user='guest', password='Guest.618',
                       database='hrs', charset='utf8mb4')
try:
    with conn.cursor() as cursor:
        affected_rows = cursor.execute('delete from tb_dept where dno=%s', (no, ))
        if affected_rows == 1:
            print('删除部门成功!')
    conn.commit()
except pymysql.MySQLError as err:
    print(err)
    conn.rollback()
finally:
    conn.close()

更改数据

import pymysql

no = int(input('部门编号: '))
name = input('部门名称: ')
loc = input('部门所在地: ')
conn = pymysql.connect(host='47.104.31.138', port=3306,
                       user='guest', password='Guest.618',
                       database='hrs', charset='utf8mb4')
try:
    with conn.cursor() as cursor:
        affected_rows = cursor.execute(
            'update tb_dept set dname=%s, dloc=%s where dno=%s',
            (name, loc, no)
        )
        if affected_rows == 1:
            print('更新部门成功!')
    conn.commit()
except pymysql.MySQLError as err:
    print(err)
    conn.rollback()
finally:
    conn.close()

查询数据库

多种查询方法都可以 输出字典 迭代器

import pymysql

conn = pymysql.connect(host='47.104.31.138', port=3306,
                       user='guest', password='Guest.618',
                       database='hrs', charset='utf8mb4')
try:
    # 第二步:获得游标对象
    with conn.cursor() as cursor:
        # 第三步:通过游标执行SQL
        cursor.execute('select dno, dname, dloc from tb_dept')
        # 第四步:通过游标抓取数据(查询结果)
        # fetchone / fetchmany / fetchall
        # 提示:如果查询结果数据体量很大,那么最好不使用fetchall,
        # 否则程序可能因为内存不足而崩溃

        # print(cursor.fetchall())

        # row = cursor.fetchone()
        # while row:
        #     print(row)
        #     row = cursor.fetchone()

        # for row in iter(lambda:coursor.fetchone(), None):
        #     print(row)

except pymysql.MySQLError as err:
    print(err)
    # conn.rollback()
finally:
    conn.close()

查询部门信息

import pymysql


class Dept:

    def __init__(self, no, name, location):
        self.no = no
        self.name = name
        self.location = location

    def __str__(self):
        return f'编号:{self.no}\n名称: {self.name}\n所在地:{self.location}'


conn = pymysql.connect(host='47.104.31.138', port=3306,
                       user='guest', password='Guest.618',
                       database='hrs', charset='utf8mb4')
try:
    with conn.cursor(pymysql.cursors.DictCursor) as cursor:
        cursor.execute(
            'select dno as no, dname as name, dloc as location from tb_dept'
        )
        dept_row = cursor.fetchone()
        while dept_row:
            # 通过获取到的部门的数据创建一个部门对象
            dept = Dept(**dept_row)
            print(dept.no, dept.name, dept.location, sep='\t')
            dept_row = cursor.fetchone()
except pymysql.MySQLError as err:
    print(err)
finally:
    conn.close()

批量插入数据

import time

import pymysql

conn = pymysql.connect(host='localhost', port=3306,
                       user='root', password='root',
                       database='hrs', charset='utf8mb4')
start = time.time()
try:
    with conn.cursor() as cursor:
        params = []
        for i in range(1, 50001):
            params.append((f'dno{i}', ))
            if i % 1000 == 0:
                cursor.executemany(
                    'insert into tb_dept (dno) values (%s)',
                    params
                )
                params.clear()
    conn.commit()
    end = time.time()
    print(f'耗时: {end - start:.3f}秒')
except pymysql.MySQLError as err:
    print(err)
    conn.rollback()
finally:
    conn.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值