pymysql的使用

pymysql是从Python连接到MySQL数据库服务器的接口,其官方文档为:https://pymysql.readthedocs.io/en/latest/

安装:pip install pymysql

对于数据库的操作,我们一般是这样的操作:
步骤1:连接数据库
步骤2:数据库的操作(增删改查)
步骤3:关闭数据库连接

以下是pymysql经常被用到的一些方法

方法描述
pymysql.connect()connect()方法返回要给数据库连接对象,参数可以传入很多,常用的参数有:host、port、user、password、database、charset,connect()创建了连接对象,执行完sql操作后,必须使用close()关闭
close()数据库连接对象的一个方法,用于关闭数据库连接
cursor()数据库连接对象的一个方法,用于获取游标对象,游标对象的execute(sql语句)方法可以执行sql语句
execute(sql)游标对象的一个方法,可以执行sql语句
commit()提交到数据库,数据库连接对象的一个方法,如果对表数据有修改的时候,就需要将修改提交到数据库,否则修改没有生效
rollback()回滚已提交的内容,,数据库连接对象的一个方法,依据事务的原子性 ,提交要么全部生效,要么全不生效,如果遇到异常,需要对已提交的内容进行回滚

数据库连接

方法描述
pymysql.connect()connect()方法返回要给数据库连接对象,参数可以传入很多,常用的参数有:host、port、user、password、database、charset,connect()创建了连接对象,执行完sql操作后,必须使用close()关闭
close()数据库连接对象的一个方法,用于关闭数据库连接
  • host:mysql服务器地址
  • port:mysql服务器连接端口,默认值为3306
  • user:用户名
  • password:密码
  • database:数据库名称
  • charset:编码方式,推荐使用"utf8mb4"

简单示例:

import pymysql

# 建立连接
conn = pymysql.connect(host="localhost",
                       port=3306,
                       user="root",
                       password="wen",
                       database="mysql",
                       charset="utf8mb4")

# 关闭连接
conn.close()

数据库操作

CRUD操作

mysql的操作一般归纳为数据库、表、表数据的增删改查

功能描述
创建表create table 表名 (column_name column_type);
删除表drop table 表名;
查询表数据select 字段名1,字段名2,…,字段名n from 表名 where xxx [limit n][offset m];
插入表数据insert into 表名(字段名1,字段名2,…,字段名n) values(值1,值2,…,值n),(值21,值22,…,值2n)… ;
更新表数据update 表名 set 字段名1=新值1,字段名2=新值2,…,字段名n=新值n where xxx;
删除表数据delete from 表名 where xxx;

示例:

import pymysql

# 建立连接
conn = pymysql.connect(host="localhost",
                       port=3306,
                       user="root",
                       password="wen",
                       database="test",
                       charset="utf8mb4")
# 执行操作(先获取游标对象,再执行sql语句)
cursor = conn.cursor()  # 获取游标对象

cursor.execute("show tables;")
print(f"当前test库的表有(创建表前):{cursor.fetchall()}")
# 创建表
creat_table_sql = """
    create table person(
    `id` int unsigned auto_increment primary key,
    `name` varchar(40) not null,
    `birthday` date);
"""
cursor.execute(creat_table_sql)
cursor.execute("show tables;")
print(f"当前test库的表有(创建表后):{cursor.fetchall()}\n")

# 插入表数据
cursor.execute("insert into person(name, birthday) values('wen', '2001-09-23'), ('xiaoba', '1998-04-17');")
conn.commit()   # 提交记录

# 查询表数据
cursor.execute("select * from person")
print(f"person插入数据后表内容为:{cursor.fetchall()}\n")

# 更新表数据
cursor.execute("update person set birthday='2001-12-17' where name='xiaoba';")
conn.commit()
cursor.execute("select * from person")
print(f"person更新数据后表内容为:{cursor.fetchall()}\n")

# 删除表数据
cursor.execute("delete from person where name='wen'")
conn.commit()
print(f"person删除数据后表内容为:{cursor.fetchall()}\n")

# 关闭连接
conn.close()

执行结果为:

当前test库的表有(创建表前):()
当前test库的表有(创建表后):(('person',),)

person插入数据后表内容为:((1, 'wen', datetime.date(2001, 9, 23)), (2, 'xiaoba', datetime.date(1998, 4, 17)))

person更新数据后表内容为:((1, 'wen', datetime.date(2001, 9, 23)), (2, 'xiaoba', datetime.date(2001, 12, 17)))

person删除数据后表内容为:()

查询操作

游标对象提供了3种获取查询记录的方法

方法描述
fetchone()获取单条记录(元组形式)
fetchmany(n)获取n条记录 (元组形式)
fetchall()获取所有结果记录(元组形式)

示例:

import pymysql

# 建立连接
conn = pymysql.connect(host="localhost",
                       port=3306,
                       user="root",
                       password="wen",
                       database="test",
                       charset="utf8mb4")
# 执行操作(先获取游标对象,再执行sql语句)
cursor = conn.cursor()  # 获取游标对象

cursor.execute("select * from person where birthday>='2000-01-01'")
result_one = cursor.fetchone()
print(type(result_one))
print(f"fetchone()查询到的内容:{result_one}\n")

cursor.execute("select * from person where birthday>='2000-01-01'")
result_3 = cursor.fetchmany(3)
print(type(result_3))
print(f"fetchmany(3)查询到的内容:{result_3}\n")

cursor.execute("select * from person where birthday>='2000-01-01'")
result_all = cursor.fetchall()
print(type(result_all))
print(f"fetchall()查询到的内容:{result_all}")

# 关闭连接
conn.close()

表内容为:
在这里插入图片描述

执行结果为:

<class 'tuple'>
fetchone()查询到的内容:(1, 'wen', datetime.date(2001, 9, 23))

<class 'tuple'>
fetchmany(3)查询到的内容:((1, 'wen', datetime.date(2001, 9, 23)), (3, '张三', datetime.date(2012, 7, 9)), (5, 'harry', datetime.date(2013, 7, 9)))

<class 'tuple'>
fetchall()查询到的内容:((1, 'wen', datetime.date(2001, 9, 23)), (3, '张三', datetime.date(2012, 7, 9)), (5, 'harry', datetime.date(2013, 7, 9)), (6, 'heng李', datetime.date(2004, 11, 26)))
执行事务

在增加、修改、删除表数据的时候,并不是说实时更新数据库的,当前连接对数据库的操作,要么全做,要么全不做。
pymysql提供了commit()和rollback()这2个方法

功能描述
commit()将游标的所有更新操作进行提交
rollback()回滚当前游标的所有操作

以下是没有执行commit()方法的示例:

import pymysql

# 建立连接
conn = pymysql.connect(host="localhost",
                       port=3306,
                       user="root",
                       password="wen",
                       database="test",
                       charset="utf8mb4")
# 执行操作(先获取游标对象,再执行sql语句)
cursor = conn.cursor()  # 获取游标对象

# 插入表数据
cursor.execute("insert into person(name, birthday) values('harry', '2004-11-23'), ('heng李', '1983-04-28');")

# 更新表数据
cursor.execute("update person set birthday='2001-12-17' where name='xiaoba';")

# 删除表数据
cursor.execute("delete from person where name='wen'")

# 查询表数据
cursor.execute("select * from person")
print(f"person表内容为:{cursor.fetchall()}\n")

# 关闭连接
conn.close()

控制台打印结果为:

person表内容为:((2, 'xiaoba', datetime.date(2001, 12, 17)), (3, '张三', datetime.date(2012, 7, 9)), (9, 'harry', datetime.date(2004, 11, 23)), (10, 'heng李', datetime.date(1983, 4, 28)))

test数据库的person表在脚本执行前后如图:
在这里插入图片描述
我们看到,在该没有进行commit的脚本中,控制台打印的数据是更新后的数据,但是实际去mysql服务器查询的时候,脚本执行前后,数据并没有变化,可以判断出:游标对象对表数据的修改并没有在表中实际生效

使用了commit()方法

import pymysql

# 建立连接
conn = pymysql.connect(host="localhost",
                       port=3306,
                       user="root",
                       password="wen",
                       database="test",
                       charset="utf8mb4")
# 执行操作(先获取游标对象,再执行sql语句)
cursor = conn.cursor()  # 获取游标对象

# 插入表数据
cursor.execute("insert into person(name, birthday) values('harry', '2004-11-23'), ('heng李', '1983-04-28');")

# 更新表数据
cursor.execute("update person set birthday='2001-12-17' where name='xiaoba';")

# 删除表数据
cursor.execute("delete from person where name='wen'")
# 将修改内容提交到数据库
conn.commit()

# 查询表数据
cursor.execute("select * from person")
print(f"person表内容为:{cursor.fetchall()}\n")

# 关闭连接
conn.close()

执行后:
控制台打印内容为:

person表内容为:((2, 'xiaoba', datetime.date(2001, 12, 17)), (3, '张三', datetime.date(2012, 7, 9)), (11, 'harry', datetime.date(2004, 11, 23)), (12, 'heng李', datetime.date(1983, 4, 28)))

mysql查询:
在这里插入图片描述
对比未使用commit()的场景,mysql查询person表的时候,person表内容更新了
rollback()方法一般是用于执行表操作错误后,对已更新的内容进行回滚(如果已经commit()成功的内容,就不回滚,一般来说服,数据库操作均使用try-catch-finally去兼容异常

import pymysql

try:
    # 建立连接
    conn = pymysql.connect(host="localhost",
                           port=3306,
                           user="root",
                           password="wen",
                           database="test",
                           charset="utf8mb4")
    # 执行操作(先获取游标对象,再执行sql语句)
    cursor = conn.cursor()  # 获取游标对象

    # 更新表数据
    cursor.execute("update person set birthdaye='2001-12-17' where name='张三';")
    # 提交修改
    conn.commit()
except Exception as e:
    # 回滚事务
    print(e)
    print("即将对数据进行回滚")
    conn.rollback()
finally:
    # 关闭连接
    conn.close()

执行结果为:

(1054, "Unknown column 'birthdaye' in 'field list'")
即将对数据进行回滚

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值