Python3.x 连接MySQL数据库

Python3.x 连接MySQL数据库

由于 MySQLdb 模块还不支持 Python3.x,所以 Python3.x 如果想连接MySQL需要安装 pymysql 模块。

pymysql 模块可以通过 pip 安装pip install PyMySQL

用pymysql连接数据库

1
2
3
4
5
6
7
8
conn = pymysql.connect(host='localhost',
port=3306,
user='root',
password='root',
db='hrs',
charset='utf8',
autocommit=False # 默认不自动提交
)
  • 常用参数说明:

    host:主机IP

    port:端口号

    user:mysql登录用户名

    password:mysql登录密码

    db:数据库名称

    charset:连接数据库采用的字符编码

    autocommit:默认值是False,DML(数据操纵语言)不会自动提交,如果为True则会自动提交

    cursorclass:pymysql.cursors.DictCursor - 设置游标的类型,查询返回的结果是以字典的方式

  • 测试是否连接成功

    1
    2
    print(conn)
    $ <pymysql.connections.Connection object at 0x05656EB0>

如果运行上面的语句不报错,并且看到了输出到控制台的值,那么我们则用pymysql连接上了MySQL数据库.

方法介绍

1
2
3
4
5
6
7
8
9
10
11
12
13
connection对象常用的方法
cursor() 使用该连接创建并返回游标
commit() 提交当前事务
rollback() 回滚当前事务
close() 关闭连接

cursor对象常用的方法和属性
execute(sql) 执行一个数据库的查询命令
fetchone() 取得结果集的下一行
fetchmany(size) 获取结果集的下几行
fetchall() 获取结果集中的所有行
rowcount 返回数据条数或影响行数
close() 关闭游标对象

在介绍上面方法使用前再看看连接数据库的代码块,其中有一个很重要的参数db (数据库名称),所以我们应当在连接数据库之前,先创建一个数据库,方便测试 pymysql 的功能

使用Python实现增删改查和事务处理

首先我们在上面说的hrs数据库中创建一张部门表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
-- 创建部门表
create table tbdept
(
dno int, -- 部门编号
dname varchar(10) not null, -- 部门名称
dloc varchar(20) not null, -- 部门所在地
primary key (dno)
);
-- 添加部门记录
insert into tbdept values
(10, '会计部', '北京'),
(20, '研发部', '成都'),
(30, '销售部', '重庆'),
(40, '运维部', '深圳');
1
2
3
4
5
6
7
8
9
10
11
12
13
def get_conn():
config = {
'host': 'localhost',
'port': 3306,
'user': 'root',
'password': 'root',
'db': 'hrs',
'charset': 'utf8',
'autocommit': False, # 默认不自动提交
'cursorclass': pymysql.cursors.DictCursor # 设置游标的类型,查询返回的结果是以字典的方式
}
conn = pymysql.connect(**config)
return conn
  • 下面我们先来看看添加的操作:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    def insert():
    """
    插入
    """
    # Connection(连接) / Cursor(游标)
    conn = get_conn()
    try:
    # 创建Cursor对象,cursor支持上下文语法,可以放在with中
    with conn.cursor() as cursor:
    # 向数据库发出sql语句
    dno = input('部门编号:')
    dname = input('部门名称:')
    dloc = input('部门地址:')
    # 如果使用字符串格式化的方式来组装SQL语句
    # 最大的风险是用被SQL注射攻击
    # sql = "insert into tbdept values (%d, '%s', '%s')" % (dno, dname, dloc)
    # result = cursor.execute(sql)
    # result = cursor.execute('insert into tbdept values (%s, %s, %s)', (dno, dname, dloc))
    # 这个方式传参是以字典的方式,但是要注意的是在占位的时候用%(name)s
    result = cursor.execute(
    'insert into tbdept values (%(dno)s, %(dname)s, %(dloc)s)',
    {'dno': dno, 'dname': dname, 'dloc': dloc}
    )
    # print('成功插入', cursor.rowcount, '条数据') # 这里cursor.rowcount是获取到受影响的行
    print('成功插入', result, '条数据')
    conn.commit()
    finally:
    conn.close()
  • 修改操作

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    def update():
    """
    修改
    """
    conn = get_conn()
    try:
    with conn.cursor() as cursor:
    dno = input('部门编号:')
    dname = input('部门名称:')
    # 这个方式传参是以字典的方式,但是要注意的是在占位的时候用%(name)s
    result = cursor.execute(
    'update tbdept set dname=%(dname)s where dno=%(dno)s',
    {'dno': dno, 'dname': dname}
    )
    # print('成功插入', cursor.rowcount, '条数据') # 这里cursor.rowcount是获取到受影响的行
    print('成功修改', result, '条数据')
    conn.commit()
    finally:
    conn.close()
  • 删除操作

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    def delete(dno):
    """
    根据编号删除
    :param dno: 编号
    """
    conn = get_conn()
    try:
    with conn.cursor() as cursor:
    # 向数据库发出sql语句
    # execute方法中占位后传参除了元组和字典外,还可以是列表
    result = cursor.execute('delete from tbdept where dno=%s', [dno])
    # 如果事务中的所有操作全部成功了最后手动提交
    conn.commit()
    print('删除成功' if result == 1 else '删除失败')
    except Exception as e:
    print(e)
    # 如果事务操作有任何一个操作发生异常,那么就会回滚事务
    conn.rollback()
    finally:
    conn.close()
  • 查询操作

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    def select():
    """
    查询
    """
    conn = get_conn()
    print(conn)
    try:
    # 创建Cursor对象
    with conn.cursor() as cursor:
    # 向数据库发出sql语句
    cursor.execute('select dno, dname, dloc from tbdept')
    result = cursor.fetchone()
    # 程序中最好不要使用fetchall(),如果库中数据量很大,那么脑补一下会有什么样的结果呢
    while result:
    print(result)
    # 取出部门名称
    # 在这里我上面连接数据时,使用了cursorclass参数,查询时返回的结果是以字典的方式
    print(result['dname'])
    result = cursor.fetchone()
    finally:
    conn.close()

到现在我们已经简单的介绍了用pymysql完成了对数据库的CURD操作

-------------本文结束感谢您的阅读-------------

本文标题:Python3.x 连接MySQL数据库

文章作者:GavinLiu

发布时间:2017年10月12日 - 09:10

最后更新:2017年10月12日 - 09:10

原始链接:http://gavinliu4011.github.io/post/64b3833f.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

请博主吃个鸡腿吧
0%