• 技术文章 >后端开发 >Python教程

    Python数据库编程

    高洛峰高洛峰2016-11-19 10:03:21原创709
    讲解Python操作数据库,完成简单的增删改查工作,以MySQL数据库为例。

    Python的MySQL数据库操作模块叫MySQLdb,需要额外的安装下。

    通过pip工具安装:pip install MySQLdb

    MySQLdb模块,我们主要就用到连接数据库的方法MySQLdb.Connect(),连接上数据库后,再使用一些方法做相应的操作。

    MySQLdb.Connect(parameters...)方法提供了以下一些常用的参数:

    wKioL1guYhOjQXvkAAA8PZ7t7wQ318.png

    php入门到就业线上直播课:进入学习

    连接对象返回的connect()函数:

    wKioL1guYhOjQXvkAAA8PZ7t7wQ318.png

    游标对象也提供了几种方法:

    wKioL1guYhOjQXvkAAA8PZ7t7wQ318.png

    13.1 数据库增删改查

    13.1.1 在test库创建一张user表,并添加一条记录

    >>> conn = MySQLdb.Connect(host='192.168.1.244',user='root',passwd='QHyCTajI',db='test',charset='utf8')
    >>> cursor = conn.cursor()
    >>> sql = "create table user(id int,name varchar(30),password varchar(30))"
    >>> cursor.execute(sql)   # 返回的数字是影响的行数
    0L    
    >>> sql = "insert into user(id,name,password) values('1','xiaoming','123456')"
    >>> cursor.execute(sql)
    1L
    >>> conn.commit()  # 提交事务,写入到数据库
    >>> cursor.execute('show tables')  # 查看创建的表
    1L
    >>> cursor.fetchall()  # 返回上一个游标执行的所有结果,默认是以元组形式返回
    ((u'user',),)
    >>> cursor.execute('select * from user')           
    1L
    >>> cursor.fetchall()
    ((1L, u'xiaoming', u'123456'),)

    13.1.2 插入多条数据

    >>> sql = 'insert into user(id,name,password) values(%s,%s,%s)'
    >>> args = [('2','zhangsan','123456'), ('3','lisi','123456'),('4','wangwu','123456')] 
    >>> cursor.executemany(sql, args)
    3L
    >>> conn.commit()
    >>> sql = 'select * from user'
    >>> cursor.execute(sql)
    4L
    >>> cursor.fetchall()
    ((1L, u'xiaoming', u'123456'), (2L, u'zhangsan', u'123456'), (3L, u'lisi', u'123456'), (4L, u'wangwu', u'123456'))

    args变量是一个包含多元组的列表,每个元组对应着每条记录。当查询多条记录时,使用此方法,可有效提高插入效率。

    13.1.3 删除用户名xiaoming的记录

    >>> sql = 'delete from user where name="xiaoming"'
    >>> cursor.execute(sql)                           
    1L
    >>> conn.commit()
    >>> sql = 'select * from user'                   
    >>> cursor.execute(sql)       
    3L
    >>> cursor.fetchall()         
    ((2L, u'zhangsan', u'123456'), (3L, u'lisi', u'123456'), (4L, u'wangwu', u'123456'))

    13.1.4 查询记录

    >>> sql = 'select * from user' 
    >>> cursor.execute(sql)         
    3L
    >>> cursor.fetchone()   # 获取第一条记录
    (2L, u'zhangsan', u'123456')
    >>> sql = 'select * from user' 
    >>> cursor.execute(sql)         
    3L
    >>> cursor.fetchmany(2) # 获取两条记录
    ((2L, u'zhangsan', u'123456'), (3L, u'lisi', u'123456'))

    13.1.4 以字典形式返回结果

    默认显示是元组形式,要想返回字典形式,使得更易处理,就用到cursor([cursorclass])中的cusorclass参数。
    传入MySQLdb.cursors.DictCursor类:
    >>> cursor = conn.cursor(MySQLdb.cursors.DictCursor)
    >>> sql = 'select * from user'
    >>> cursor.execute(sql)
    3L
    >>> cursor.fetchall()
    ({'password': u'123456', 'id': 2L, 'name': u'zhangsan'}, {'password': u'123456', 'id': 3L, 'name': u'lisi'}, {'password': u'123456', 'id': 4L, 'name': u'wangwu'})

    13.2 遍历查询结果

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import MySQLdb
    try:
        conn = MySQLdb.Connect(host='127.0.0.1', port=3306, user='root', passwd='123456', connect_timeout=3, charset='utf8')
        cursor = conn.cursor()
        sql = "select * from user"
        cursor.execute(sql)
        for i in cursor.fetchall():
            print i
    except Exception, e:
        print ("Connection Error: " + str(e))
    finally:
        conn.close()
         
    # python test.py
    (2L, u'zhangsan', u'123456')
    (3L, u'lisi', u'123456')
    (4L, u'wangwu', u'123456')

    使用for循环遍历查询结果,并增加了异常处理。

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。

    前端(VUE)零基础到就业课程:点击学习

    清晰的学习路线+老师随时辅导答疑

    自己动手写 PHP MVC 框架:点击学习

    快速了解MVC架构、了解框架底层运行原理

    专题推荐:Python
    上一篇:python析构函数和特殊的call方法 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • ❤️‍🔥共22门课程,总价3725元,会员免费学• ❤️‍🔥接口自动化测试不想写代码?• Python NumPy教程之数据类型对象• 使用Python处理KNN分类算法• Python标准库中的logging用法示例• python发腾讯微博代码分享• 浅谈Python的Django框架中的缓存控制
    1/1

    PHP中文网