• Python学习笔记六:数据库操作


    一:Python操作数据库的流程

    二:开发环境准备

    1:开发工具PyCharm

    2:Python操作mysql的工具:需要安装Python-Mysql Connector,网址:https://sourceforge.net/projects/mysql-python/ ,下载完成后点击启动安装即可。

    3:数据库桌面工具:SQLYog

    三:Python操作数据库的两大对象之数据库连接对象——Connection

    connection主要用于建立Python与数据库之间的网络连接。

    创建方法:MySQLdb.Connect(参数)

    参数列表主要有:

    数据库连接对象常用方法:

    测试:

    import MySQLdb
    
    conn = MySQLdb.connect(host="127.0.0.1",port=3306,user="root",passwd='root',db='testpython',charset='utf8')
    cur=conn.cursor()
    
    print conn
    print cur
    
    cur.close()
    conn.close()
    
    
    结果:
    <_mysql.connection open to '127.0.0.1' at 2a449b8>
    <MySQLdb.cursors.Cursor object at 0x02AE8A10>

    四:Python操作数据库的两大对象之数据库连接对象——Cursor

    游标对象Cursor,用于执行具体的数据库操作语句以及获取结果。

    cursor支持以下方法调用:

    三个fetchXX方法,可以对 execute方法执行的结果进行遍历;rowcount方法可以获取execute方法对数据库操作的记录行数。

    五:增删查改操作

    查:主要使用execute()/fetchXX语句;

    增、改、删:需要关闭自动提交事务(MySQLdb模块默认关闭了自动提交)、使用execute()语句执行操作、捕捉异常进行回滚/执行完毕提交事务

    import MySQLdb
    
    #1:创建数据库连接
    conn = MySQLdb.connect(host="127.0.0.1",port=3306,user="root",passwd='root',db='testpython',charset='utf8')
    #2:创建cursor
    cur=conn.cursor()
    
    #3:使用cursor执行查询
    cur.execute("select * from test")
    first=cur.fetchone()
    print first
    
    #4:在try-except语句块中执行增、删、改操作
    try:
        cur.execute("insert into test(say) VALUES ('the first content')")
        print cur.rowcount
    
        cur.execute("update test set say='I have been updated' where id = 1")
        print cur.rowcount
    
        cur.execute("select * from test")
        all = cur.fetchall()
        print all
    
        cur.execute("delete from test where id = 1")
        print cur.rowcount
    
        cur.execute("select * from test")
        all = cur.fetchall()
        print all
    #5:提交事务
        conn.commit()
    except Exception:
    #6:捕捉异常进行回滚
        conn.rollback()
    finally:
    #7:关闭cursor和connection
        cur.close()
        conn.close()
  • 相关阅读:
    10th blog:箭头函数
    10th blog:Event Flow
    12th:MAP.API
    10th blog:For each···in / For···in / For···of
    10th blog:Object
    Web第九周作业:History of Program(1950--2020)
    Web作业:Regular Expression
    Web作业:specific word count (index of )
    Web第七周作业:DOM&BOM
    MAP
  • 原文地址:https://www.cnblogs.com/ygj0930/p/6961499.html
Copyright © 2020-2023  润新知