一、数据库操作

1.1 安装pymysql

pip install pymysql

1.2 连接数据库

python连接test数据库

import pymysql

host = 'localhost'      # 主机地址
username = 'root'       # 数据库用户名
password = ''           # 数据库密码
db_name = 'test'        # 数据库名称

# 创建connect对象
connect = pymysql.connect(host=host, user=username, password=password, database=db_name)

# 获取游标对象
cursor = connect.cursor()

# 查询数据库版本
cursor.execute('select version()')

# 从查询结果集中获取下一行数据,返回值为一个值的序列
result = cursor.fetchone()

# 打印结果
print(result)

# 关闭游标
cursor.close()

# 关闭数据库连接
connect.close()

执行结果:
(‘10.4.17-mariadb’,)

1.3 创建数据表

创建一个默认编码格式为utf8的数据表users

id:int类型,不能为空,有自增属性,主键约束

name:varchar类型,长度最多为10字符,可以为空

age:int类型,可以为空

import pprint
import pymysql

host = 'localhost'      # 主机地址
username = 'root'       # 数据库用户名
password = ''           # 数据库密码
db_name = 'test'        # 数据库名称

# 创建connect对象
connect = pymysql.connect(host=host, user=username, password=password, database=db_name)

# 获取游标对象
cursor = connect.cursor()

# 创建数据表的sql命令
create_sql = '''
create table `users`(
    `id` int not null auto_increment,
    `name` varchar(10) null,
    `age` int null,
    primary key (`id`))
    default character set = utf8;
'''
# 创建数据表
cursor.execute(create_sql)

# 查询我们创建的数据表的结构
cursor.execute('desc users')

# 从查询结果中获取结果的所有(或者剩余)行数据,返回值为包含序列的序列(例如元组序列)
result = cursor.fetchall()

# 打印结果
pprint.pprint(result)

# 关闭游标
cursor.close()

# 关闭数据库连接
connect.close()

执行结果:
((‘id’, ‘int(11)’, ‘no’, ‘pri’, none, ‘auto_increment’),
 (‘name’, ‘varchar(10)’, ‘yes’, ”, none, ”),
 (‘age’, ‘int(11)’, ‘yes’, ”, none, ”))

1.4 插入,查询数据

插入3行数据:

id:1,name:路飞,age:18
id:2,name:娜美,age:19
id:3,name:索隆,age:20

import pprint
import pymysql

host = 'localhost'      # 主机地址
username = 'root'       # 数据库用户名
password = ''           # 数据库密码
db_name = 'test'        # 数据库名称

# 创建connect对象,插入中文时需要指定编码格式
connect = pymysql.connect(host=host, user=username, password=password, database=db_name, charset='utf8')

# 获取游标对象查询返回字典
cursor = connect.cursor(pymysql.cursors.dictcursor)

# 插入数据的sql命令
insert_sql = '''
insert into users (id, name, age)
    values (1, '路飞', 18),(2, '娜美', 19),(3, '索隆', 20)
'''

try:
    # 插入数据到数据表
    cursor.execute(insert_sql)
    # 提交任何挂起的事务到数据库
    connect.commit()
except exception as e:
    # 发送数据回滚,回滚到事务开始时的状态
    connect.rollback()

# 查询数据
cursor.execute('select * from users')

# 只返回一行数据
# result_one = cursor.fetchone()
# print('---fetchone---')
# pprint.pprint(result_one)

# 返回全部数据
result_all = cursor.fetchall()
print('---fetchall---')
pprint.pprint(result_all)

# 关闭游标
cursor.close()

# 关闭数据库连接
connect.close()

执行结果:
—fetchall—
[{‘age’: 18, ‘id’: 1, ‘name’: ‘路飞’},
 {‘age’: 19, ‘id’: 2, ‘name’: ‘娜美’},
 {‘age’: 20, ‘id’: 3, ‘name’: ‘索隆’}]

1.5 更新,查询数据

更新数据id:3,name:山治,age:21

import pprint
import pymysql

host = 'localhost'      # 主机地址
username = 'root'       # 数据库用户名
password = ''           # 数据库密码
db_name = 'test'        # 数据库名称

# 创建connect对象,插入中文时需要指定编码格式
connect = pymysql.connect(host=host, user=username, password=password, database=db_name, charset='utf8')

# 获取游标对象查询返回字典
cursor = connect.cursor(pymysql.cursors.dictcursor)

# 查询数据
cursor.execute('select * from users')

# 返回更新前全部数据
result_all = cursor.fetchall()
print('---更新前---')
pprint.pprint(result_all)

# 更新数据的sql命令
update_sql = '''
	update users set name = '山治',age = 21 where id = 3
'''

try:
    # 更新数据到数据表
    cursor.execute(update_sql)
    # 提交任何挂起的事务到数据库
    connect.commit()
except exception as e:
    # 发送数据回滚,回滚到事务开始时的状态
    connect.rollback()

# 查询数据
cursor.execute('select * from users')

# 返回更新后全部数据
result_all = cursor.fetchall()
print('---更新后---')
pprint.pprint(result_all)

# 关闭游标
cursor.close()

# 关闭数据库连接
connect.close()

执行结果:
—更新前—
[{‘age’: 18, ‘id’: 1, ‘name’: ‘路飞’},
 {‘age’: 19, ‘id’: 2, ‘name’: ‘娜美’},
 {‘age’: 20, ‘id’: 3, ‘name’: ‘索隆’}]
—更新后—
[{‘age’: 18, ‘id’: 1, ‘name’: ‘路飞’},
 {‘age’: 19, ‘id’: 2, ‘name’: ‘娜美’},
 {‘age’: 21, ‘id’: 3, ‘name’: ‘山治’}]

1.6 删除,查询数据

删除'age': 19, 'id': 2, 'name': '娜美'该行数据

import pprint
import pymysql

host = 'localhost'      # 主机地址
username = 'root'       # 数据库用户名
password = ''           # 数据库密码
db_name = 'test'        # 数据库名称

# 创建connect对象,插入中文时需要指定编码格式
connect = pymysql.connect(host=host, user=username, password=password, database=db_name, charset='utf8')

# 获取游标对象查询返回字典
cursor = connect.cursor(pymysql.cursors.dictcursor)

# 查询数据
cursor.execute('select * from users')

# 返回删除前全部数据
result_all = cursor.fetchall()
print('---删除前---')
pprint.pprint(result_all)

# 删除数据的sql命令
update_sql = '''
	delete from users where id = 2
'''

try:
    # 删除数据表的数据
    cursor.execute(update_sql)
    # 提交任何挂起的事务到数据库
    connect.commit()
except exception as e:
    # 发送数据回滚,回滚到事务开始时的状态
    connect.rollback()

# 查询数据
cursor.execute('select * from users')

# 返回删除后全部数据
result_all = cursor.fetchall()
print('---删除后---')
pprint.pprint(result_all)

# 关闭游标
cursor.close()

# 关闭数据库连接
connect.close()

执行结果:
—删除前—
[{‘age’: 18, ‘id’: 1, ‘name’: ‘路飞’},
 {‘age’: 19, ‘id’: 2, ‘name’: ‘娜美’},
 {‘age’: 21, ‘id’: 3, ‘name’: ‘山治’}]
—删除后—
[{‘age’: 18, ‘id’: 1, ‘name’: ‘路飞’}, {‘age’: 21, ‘id’: 3, ‘name’: ‘山治’}]

二、连接与游标对象的方法

2.1 连接对象的方法

  • .close()方法:

马上关闭数据连接(而不是当__del__方法被调用的时候)。此后连接变得不可用,再次访问本连接对象会触发一个错误,使用本连接对象的游标对象,也会导致例外发生。在关闭连接对象之前,没有提交(commit)对数据库的改变将会导致一个隐含的回滚动作(rollback),这将丢弃之前的数据改变操作。

  • .commit()方法:

提交任何挂起的事务到数据库中。

  • .rollback()方法:

对于支持事务的数据库。调用此方法将导致数据库回滚到事务开始时的状态。

  • .cursor()方法:

方法返回给定连接上建立的游标对象(cursor object),如果数据库没有提供对应的游标对象,那么有程序来模拟实现游标功能。

2.2 游标对象的方法

  • .close()方法:

立即关闭游标(不论__del__方法是否已被调用),此后游标对象就变得不可用了。

  • .execute(operation[,parameters])方法:

准备和执行数据库操作。所提供的参数将会被绑定到语句中的变量,变量的定义和数据库模块有关。

  • .executemany(operation,seq_of_parameters)方法:

准备和执行数据库操作,然后以序列形式的函数来执行该操作。

  • .fetchone()方法:

从查询结果中获取下一行数据,返回值为一个值的序列,如果没有更多数据则返回none。

  • .fetchmany([size=cursor.arraysize])方法:

从查询结果中获取下一组行数据,返回值为包含序列的序列,如果没有数据返回时,则返回空序列。每次调用要获取的行数由参数指定,如果没有指定行数,则游标的arraysize属性决定要获取的行数。

  • .fetchall()方法:

从查询结果中获取所有(或者剩余)行数据,返回值为包含序列的序列。

  • .nextset()方法:

此方法将游标跳到下一个可用的结果集并丢弃当前结果集的所有行,如果没有更有查询结果集则返回none,否则返回true,接下来的fetch操作将会从新结果集返回数据了。

  • .setinputsizes(sizes)方法:

此方法可用在调用.execute系列方法之前使用,用于预定义内存区域。size参数接收一个序列类型的值,每一个元素对应一个输入参数,该元素应该是一个类型对象,对于将要使用的参数,或者是一个整数,用于指定字符串的最大长度。如果元素是none,则没有预定义的内存区域作为保留区域。

  • .setoutputsize(size[,column])方法:

为一个很大的列设置缓冲区大小,不指定将使用默认大小。

三、事务

事务是数据库管理系统执行过程中的一个逻辑单位,由一个有限的数据库操作序列构成,事务的目的性是为了保证数据的一致性。假设银行转账操作,从a账户转账100元到b账户需要进行至少两次的数据库修改操作,a账户余额需要减少100元,b账户余额需要增加100元,如果因为由于外部原因导致程序意外终止,就会操作数据出错,事务就是防止此情况的发生。

数据库事务拥有四个特性,习惯称之为acid特性:

1、原子性(atomicity):事务作为一个整体被执行,包含在其中的对数据库的操作要么全部被执行,要么不执行。
2、一致性(consistency):事务应确保数据库的状态从一个一致状态转变为另一个一致状态,一致状态的含义是数据库中的数据应满足完整性约束。
3、隔离性(isolation):多个事务并发执行时,一个事务的执行不应影响其他事务的执行。
4、持久性(durability):已被提交的事务对数据库的修改应该永久保存在数据库中。

import pprint
import pymysql

host = 'localhost'      # 主机地址
username = 'root'       # 数据库用户名
password = ''           # 数据库密码
db_name = 'test'        # 数据库名称

# 创建connect对象,插入中文时需要指定编码格式
connect = pymysql.connect(host=host, user=username, password=password, database=db_name, charset='utf8')

# 获取游标对象查询返回字典
cursor = connect.cursor(pymysql.cursors.dictcursor)

# 正确的插入数据的sql命令
insert_sql1 = '''
insert into users (name, age)
    values ('罗宾', 18),('乔巴', 16)
'''

# 错误的插入数据的sql命令
insert_sql2 = '''
insert into users (name, age)
    values ('弗兰奇')
'''

try:
    # 插入数据到数据表
    cursor.execute(insert_sql1)
    cursor.execute(insert_sql2)
    # 提交任何挂起的事务到数据库
    connect.commit()
except exception as e:
    # 执行失败发送数据回滚,回滚到事务开始时的状态
    connect.rollback()

# 查询数据
cursor.execute('select * from users')

# 返回全部数据
result_all = cursor.fetchall()
print('---fetchall---')
pprint.pprint(result_all)

# 关闭游标
cursor.close()

# 关闭数据库连接
connect.close()

上例中执行了两条sql语句,一条正确的一条错误的,只要有一个错误,两条都不会生效,rollback方法会回滚当前游标的所有操作。

到此这篇关于python基础之操作mysql数据库的文章就介绍到这了,更多相关python操作mysql内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!