数据库中pymysql模块的使用

pymysql 模块

使用步骤:

  核心类Connect链接用和Cursor读写用

  1. 与数据库服务器建立链接

  2. 获取游标对象(用于发送和接收数据)

  3. 用游标执行sql语句

  4. 使用fetch 方法来获取执行的结果

  5. 关闭链接 ,先关闭游标,再关链接

游标的常用方法:

  1.创建游标 conn.cursor(指定查询结果的数据类型)

  2.excute 执行sql

  3. fetchone(当sql只有一条记录时) many(sql有多条并且需要指定条数) all(多条)

  4.scroll  用于修改游标的当前位置。

  注意:pymysql  默认不提交修改,但是注意(指的是对表中记录的操作不提交),像删除库和删除表是无法撤销的。

"""
# 创建链接得到一个链接对象
conn = pymysql.Connect(
    host="127.0.0.1",    # 数据库服务器主机地址
    user="root",  # 用户名
    password="admin", # 密码
    database="day42", #数据库名称
    port=3306, # 端口号 可选 整型
    charset="utf8" # 编码  可选
)
# 获取游标对象  pymysql.cursors.DictCursor指定 返回的结果类型 为字典  默认是元祖类型
cursor = conn.cursor(pymysql.cursors.DictCursor)

# 查询数据
sql = "select *from emp"

# 执行sql  如果是select 语句返回的是 查询的条数
res = cursor.execute(sql)
print(res)

# 获取查询的结果
# print(cursor.fetchall())
# print(cursor.fetchone())
# print(cursor.fetchone())
# print(cursor.fetchmany(1))
# print(cursor.fetchall())

# scroll
print(cursor.fetchone())
cursor.scroll(-1)
print(cursor.fetchall())


# 关闭链接
cursor.close()
conn.close()

添加,删除数据库中的内容

import pymysql
# 创建链接得到一个链接对象
conn = pymysql.Connect(
    host="127.0.0.1",    # 数据库服务器主机地址
    user="root",  # 用户名
    password="admin", # 密码
    database="day42", #数据库名称
    port=3306, # 端口号 可选 整型
    charset="utf8" # 编码  可选
)
# 获取游标对象  pymysql.cursors.DictCursor指定 返回的结果类型 为字典  默认是元祖类型
cursor = conn.cursor(pymysql.cursors.DictCursor)

# # 添加数据
# res = cursor.execute("insert into emp values(100,'胡歌','男',30,1,'job',60000)")
# if res:
#     print("插入成功")
# else:
#     print("插入失败")


# 提交修改   因为pymysql 模块默认是启用事务的  你的sql语句 如果不提交 相当于没有执行

# conn.commit()
# res = cursor.execute("drop database day42")


# res = cursor.execute("delete from t1 where id = 1")
# print(res)

try:
    cursor.execute("update moneyTable set money = money - 50 where name = '小明'")
    #如果小花的账户出问题了 无法更新数据 那就需要回滚
    cursor.execute("update moneyTable set money = money + 50 where name = '小花'")
    conn.commit()
except:
    conn.rollback()



cursor.close()
conn.close()

#  小明有100块 准备给小花转50
# update moneyTable set money = money - 50 where name = "小明";
# 发生一些别错误  如果发生了错误 就执行撤销操作 rollback;
# update moneyTable set money = money + 50 where name = "小花";
View Code

 

posted @ 2018-09-17 17:32  薛才昌  阅读(219)  评论(0编辑  收藏  举报