首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 使用pymysql模块操作数据库

Python 使用pymysql模块操作数据库

作者头像
Devops海洋的渔夫
发布2019-06-02 13:46:31
9960
发布2019-06-02 13:46:31
举报
文章被收录于专栏:Devops专栏Devops专栏

Python 中操作 MySQL 步骤

看完了上面的这个操作流程,那么python操作数据库可以用上面模块来操作呢?

目前比较流行的就是pymysql,下面来看看介绍。

pymysql介绍

PyMySQL是一个纯Python写的MySQL客户端,它的目标是替代MySQLdb,可以在CPython、PyPy、IronPython和Jython环境下运行。PyMySQL在MIT许可下发布。 PyMySQL的性能和MySQLdb几乎相当,如果对性能要求 不是特别的强,使用PyMySQL将更加方便。 PyMySQL的使用方法和MySQLdb几乎一样。

之前我在实战系列写了几篇关于操作mysql的文章,如下:

Python采用并发查询mysql以及调用API灌数据 (一)

Python采用并发查询mysql以及调用API灌数据 (二) - PyMysql操作数据库基本类封装

下面再来一番系统概念,进入引申后面web开发框架需要用到的数据以及知识。

引入模块

在py文件中引入pymysql模块

from pymysql import *

Connection 对象

conn=connect(参数列表)

用于建立与数据库的连接

创建对象:调用connect()方法

参数列表:

  • 参数host:连接的mysql主机,如果本机是'localhost'
  • 参数port:连接的mysql主机的端口,默认是3306
  • 参数database:数据库的名称
  • 参数user:连接的用户名
  • 参数password:连接的密码
  • 参数charset:通信采用的编码方式,推荐使用utf8

对象的方法

  • close()关闭连接
  • commit()提交
  • cursor()返回Cursor对象,用于执行sql语句并获得结果
  • execute(operation , parameters )执行语句,返回受影响的行数,主要用于执行- -
  • insert、update、delete语句,也可以执行create、alter、drop等语句
  • fetchone()执行查询语句时,获取查询结果集的第一个行数据,返回一个元组
  • fetchall()执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回

Cursor对象

  • 用于执行sql语句,使用频度最高的语句为select、insert、update、delete
  • 获取Cursor对象:调用Connection对象的cursor()方法 cs1=conn.cursor()

对象的属性

  • rowcount只读属性,表示最近一次execute()执行后受影响的行数
  • connection获得当前连接对象

安装PyMysql

pip install pymysql

好了,安装好了pymysql模块之后,首先需要创建mysql的相关数据,方便后续使用。

Mysql创建数据库test_db

CREATE DATABASE IF NOT EXISTS test_db CHARACTER SET utf8 COLLATE utf8_general_ci;

Mysql创建表 - 胖子们的爱好表fatboy_hobby

create table fatboy_hobby(
    id int unsigned primary key auto_increment not null,
    name varchar(40) default null COMMENT "肥仔名称",
    hobby varchar(40) default null COMMENT "肥仔爱好",
    professional varchar(40) default null COMMENT "肥仔职业",
    address varchar(40) default null COMMENT "肥仔居住地"
);

Mysql插入数据

insert into fatboy_hobby VALUES(null,"胖子老板","斗地主","小卖铺老板","西九龙");
insert into fatboy_hobby VALUES(null,"肥仔白","打dota、吃槟榔","挨踢攻城狮","铜锣湾");
insert into fatboy_hobby VALUES(null,"肥仔超","吃槟榔、养养猫","挨踢攻城狮","大上海");

好了,创建有了一个表的数据了,那么下面可以使用pymysql来进行增删查改的操作。

使用pymysql查询一行数据fetchone()

# -*- coding: utf-8 -*-
from pymysql import *

def main():
    # 创建Connection连接
    conn = connect(host='localhost',port=3306,user='root',password='',database='test_db',charset='utf8')
    # 获得Cursor对象
    cs1 = conn.cursor()
    # 执行select语句,并返回受影响的行数:查询一条数据
    count = cs1.execute('select * from fatboy_hobby;')
    # 打印受影响的行数
    print("查询到%d条数据:" % count)

    for i in range(count):
        # 获取查询的结果
        result = cs1.fetchone()
        # 打印查询的结果
        print(result)
        # 获取查询的结果

    # 关闭Cursor对象
    cs1.close()
    conn.close()

if __name__ == '__main__':
    main()

运行如下:

G:\Python27\python.exe F:/pythonProject/pymysqltest/mysqltest.py
查询到3条数据:
(1, u'\u80d6\u5b50\u8001\u677f', u'\u6597\u5730\u4e3b', u'\u5c0f\u5356\u94fa\u8001\u677f', u'\u897f\u4e5d\u9f99')
(2, u'\u80a5\u4ed4\u767d', u'\u6253dota\u3001\u5403\u69df\u6994', u'\u6328\u8e22\u653b\u57ce\u72ee', u'\u94dc\u9523\u6e7e')
(3, u'\u80a5\u4ed4\u8d85', u'\u5403\u69df\u6994\u3001\u517b\u517b\u732b', u'\u6328\u8e22\u653b\u57ce\u72ee', u'\u5927\u4e0a\u6d77')

使用pymysql查询多行数据fetchall()

# -*- coding: utf-8 -*-
from pymysql import *

def main():
    # 创建Connection连接
    conn = connect(host='localhost',port=3306,user='root',password='',database='test_db',charset='utf8')
    # 获得Cursor对象
    cs1 = conn.cursor()
    # 执行select语句,并返回受影响的行数:查询一条数据
    count = cs1.execute('select * from fatboy_hobby;')
    # 打印受影响的行数
    print("查询到%d条数据:" % count)

    # for i in range(count):
    #     # 获取查询的结果
    #     result = cs1.fetchone()
    #     # 打印查询的结果
    #     print(result)
    #     # 获取查询的结果

    result = cs1.fetchall()
    print(result)

    # 关闭Cursor对象
    cs1.close()
    conn.close()

if __name__ == '__main__':
    main()

运行如下:

查询到3条数据:
((1, u'\u80d6\u5b50\u8001\u677f', u'\u6597\u5730\u4e3b', u'\u5c0f\u5356\u94fa\u8001\u677f', u'\u897f\u4e5d\u9f99'), (2, u'\u80a5\u4ed4\u767d', u'\u6253dota\u3001\u5403\u69df\u6994', u'\u6328\u8e22\u653b\u57ce\u72ee', u'\u94dc\u9523\u6e7e'), (3, u'\u80a5\u4ed4\u8d85', u'\u5403\u69df\u6994\u3001\u517b\u517b\u732b', u'\u6328\u8e22\u653b\u57ce\u72ee', u'\u5927\u4e0a\u6d77'))

使用pymysql增加数据

# -*- coding: utf-8 -*-
from pymysql import *

def main():
    # 创建Connection连接
    conn = connect(host='localhost',port=3306,user='root',password='',database='test_db',charset='utf8')
    # 获得Cursor对象
    cs1 = conn.cursor()

    # 执行insert语句,并返回受影响的行数:添加一条数据
    # 增加
    count = cs1.execute('insert into fatboy_hobby VALUES(null,"肥仔白","打dota、吃槟榔","挨踢攻城狮","铜锣湾");')
    #打印受影响的行数
    print(count)

    # 提交之前的操作,如果之前已经之执行过多次的execute,那么就都进行提交
    conn.commit()

    # 关闭Cursor对象
    cs1.close()
    conn.close()

if __name__ == '__main__':
    main()

运行如下:

G:\Python27\python.exe F:/pythonProject/pymysqltest/mysqltest.py
1

Process finished with exit code 0

使用pymysql更新数据

# -*- coding: utf-8 -*-
from pymysql import *

def main():
    # 创建Connection连接
    conn = connect(host='localhost',port=3306,user='root',password='',database='test_db',charset='utf8')
    # 获得Cursor对象
    cs1 = conn.cursor()

    # 更新
    count = cs1.execute('update fatboy_hobby set name="小肥仔是李白" where id="4"')
    #打印受影响的行数
    print(count)

    # 提交之前的操作,如果之前已经之执行过多次的execute,那么就都进行提交
    conn.commit()

    # 关闭Cursor对象
    cs1.close()
    conn.close()

if __name__ == '__main__':
    main()

运行如下:

G:\Python27\python.exe F:/pythonProject/pymysqltest/mysqltest.py
1

Process finished with exit code 0

使用pymysql删除数据

# -*- coding: utf-8 -*-
from pymysql import *

def main():
    # 创建Connection连接
    conn = connect(host='localhost',port=3306,user='root',password='',database='test_db',charset='utf8')
    # 获得Cursor对象
    cs1 = conn.cursor()

    # 删除
    count = cs1.execute('delete from fatboy_hobby where id=4')
    #打印受影响的行数
    print(count)

    # 提交之前的操作,如果之前已经之执行过多次的execute,那么就都进行提交
    conn.commit()

    # 关闭Cursor对象
    cs1.close()
    conn.close()

if __name__ == '__main__':
    main()

运行如下:

G:\Python27\python.exe F:/pythonProject/pymysqltest/mysqltest.py
1

Process finished with exit code 0

参数化

sql语句的参数化,可以有效防止sql注入 注意:此处不同于python的字符串格式化,全部使用%s占位

# -*- coding: utf-8 -*-
from pymysql import *

def main():
    # 创建Connection连接
    conn = connect(host='localhost',port=3306,user='root',password='',database='test_db',charset='utf8')
    # 获得Cursor对象
    cs1 = conn.cursor()

    # 构造参数列表
    params = ["肥仔白"]
    # 执行select语句,并返回受影响的行数:查询所有数据
    count = cs1.execute('select * from fatboy_hobby where name=%s', params)
    # 注意:
    # 如果要是有多个参数,需要进行参数化
    # 那么params = [数值1, 数值2....],此时sql语句中有多个%s即可

    # 打印受影响的行数
    print(count)

    # 获取查询的结果
    result = cs1.fetchall()

    print("result=%s" % result)

    # 提交之前的操作,如果之前已经之执行过多次的execute,那么就都进行提交
    conn.commit()

    # 关闭Cursor对象
    cs1.close()
    conn.close()

if __name__ == '__main__':
    main()

运行如下:

G:\Python27\python.exe F:/pythonProject/pymysqltest/mysqltest.py
1
result=(2, u'\u80a5\u4ed4\u767d', u'\u6253dota\u3001\u5403\u69df\u6994', u'\u6328\u8e22\u653b\u57ce\u72ee', u'\u94dc\u9523\u6e7e')

Process finished with exit code 0
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.01.04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Python 中操作 MySQL 步骤
  • pymysql介绍
  • 引入模块
  • Connection 对象
    • 对象的方法
      • Cursor对象
        • 对象的属性
          • 安装PyMysql
          • Mysql创建数据库test_db
          • Mysql创建表 - 胖子们的爱好表fatboy_hobby
          • Mysql插入数据
          • 使用pymysql查询一行数据fetchone()
            • 使用pymysql查询多行数据fetchall()
              • 使用pymysql增加数据
                • 使用pymysql更新数据
                  • 使用pymysql删除数据
                    • 参数化
                    相关产品与服务
                    云数据库 SQL Server
                    腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
                    领券
                    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档