Python学习笔记之操作MySQL数据库

使用 Python DB API 访问数据库流程:

  1. 创建 connection (建立网络连接)
  2. 获取 cursor (交互对象)
  3. 使用 cursor.execute() 执行 SQL 语句 (查询、增、删、更改等,结果返回到本地缓存)
  4. 使用 cursor.fatch*() 获取并处理数据 (从本地缓存获取,以 tuple 形式返回)
  5. 关闭 cursor
  6. 关闭 connection

cursor 游标对象的方法:

execute( op ) 执行一条查询或操作命令,结果返回到本地缓存
fetchone() 从本地结果集中取下一条,以一维 tuple 的形式返回
fetchmany(size) 从本地结果集中取下几条,以二维 tuple 的形式返回
fetchall() 从本地结果集中取所有剩下的,以二维 tuple 的形式返回
rowcount 最近一次 execute 返回数据的行数或影响行数
close() 关闭游标对象

事务:访问和更新数据库的一个执行单元,可以看成由多次数据库操作组成

autocommit(False) 关闭自动 commit
commit() 正常结束事务
rollback() 执行回滚操作

Python 操作MySQL数据库:(Python 3.0+ 需要安装 PyMySQL:pip install PyMySQL)

import pymysql
import time

#连接数据库
connect = pymysql.connect(host='localhost', user='root', passwd='', db='test')
#获取游标对象
cursor = connect.cursor()

try:
    #查询user表所有信息
    cursor.execute('select * from user')
    #取一条信息
    one = cursor.fetchone()
    #取下两条信息
    many = cursor.fetchmany(2)
    #取剩下所有信息
    alli = cursor.fetchall()

    print (one)
    print (many)
    print (alli)

    #插入一条信息
    cursor.execute("insert into user(user_name, timestamps) values('xiaoming', %s)" %time.time())
    print (cursor.rowcount)
    #删除一条信息
    cursor.execute("delete from user where id = 3")
    print (cursor.rowcount)
    #更新一条信息
    cursor.execute("update user set user_name='xiaotian' where id=4")
    print (cursor.rowcount)

    #正常结束事务
    connect.commit()

#捕获异常
except Exception as e:
    print (e)
    #发生异常时执行回滚
    connect.rollback()

#关闭游标对象
cursor.close()
#关闭连接
connect.close()

猜你喜欢

转载自blog.csdn.net/qq_37509235/article/details/80533594