python常识系列24-->python操作mysql之pymysql

前言

  1. pymsql是Python中操作MySQL的模块
  2. 程序在运行时,数据都是在内存中的。当程序终止时,通常需要将数据保存在磁盘上。

安装模块

pip install PyMySql

基本使用

## 使用 connect 函数创建连接对象,此连接对象提供关闭数据库、事务回滚等操作。
connect = pymysql.connect(host='127.0.0.1',
                     user='root',
                     password='pwd',
                     database='database_name')
# 获取游标
start = connect.cursor()
#默认获取数据的格式为元组格式

cursor = db.cursor(cursor=pymysql.cursors.DictCursor)
#设置cursor设置为pymysql.cursors.DictCursor,可以将显示数据为 字典格式

cursor.scroll(1,mode='relative')  # 相对当前位置移动
cursor.scroll(2,mode='absolute') # 相对绝对位置移动
# 第一个值为移动的行数,整数为向下移动,负数为向上移动,mode指定了是相对当前位置移动,还是相对于首行移动

# 执行sql语句
start.execute()
    # 执行单条语句
start.executemany()
    # 执行多条语句

#获取单条数据
dp = start.fetchone()

# 获取所有数据
dp = start.fetchall()

# 获取指定条数数据
dp = start.fetchone(3)
    #获取3条数据

# 关闭数据库连接
db.close()

具体实例之查询select

import pymysql

# 创建数据库连接对象
connect = pymysql.connect(host='127.0.0.1',
                          user='root',
                          password='pwd',
                          database='database_name')
# 创建游标对象
cursor = connect.cursor()

table_name = 'school_info_table'
sql = "SELECT * FROM %s WHERE schoolname LIKE '%深圳%' " % table_name
try:
    cursor.execute(sql)  # 执行sql语句,也可执行数据库命令,如:show tables
    result = cursor.fetchall()  # 所有结果
    print(result)
except Exception as e:
    connect.rollback()
    print("select Fail")
    print(e)
finally:
    cursor.close()  # 关闭当前游标
    connect.close()  # 关闭数据库连接

具体实例之修改update

import pymysql

# 创建数据库连接对象
connect = pymysql.connect(host='127.0.0.1',
                          user='root',
                          password='pwd',
                          database='database_name')
# 创建游标对象
cursor = connect.cursor()

table_name = 'table_name '
user_id = 'yyy'
user_no = 'xxx'
sql = "UPDATE %s SET user_no = '%s' WHERE user_id = '%s'" % (table_name, user_no, user_id)
try:
    cursor.execute(sql)  # 执行sql语句,也可执行数据库命令,如:show tables
    connect.commit()  # 增删改,必须执行事务
    print("update success")
except Exception as e:
    connect.rollback()  # 若出现失败,进行回滚
    print("update fail")
    print(e)
finally:
    cursor.close()  # 关闭当前游标
    connect.close()  # 关闭数据库连接
  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

挨踢~小先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值