python操作mysql / mysql 增删查改语句

PyMySQL安装/方法介绍

PyMySQL是由python编写的,速度上比不上 MySQLdb,但是他安装非常方便同时也兼容 MySQL-python

pip install pymssql

基本方法介绍

close():关闭此connect对象
commit():提交当前事务
rollback():取消当前事务
cursor():创建游标对象

关于游标

游标是一段私有的SQL工作区,也就是一段内存区域,用于暂时存放受SQL语句影响到的数据。通俗理解就是将受影响的数据暂时放到了一个内存区域的虚表中,而这个虚表就是游标。

也就是说在commit之前你操作的都是这个游标,操作错误你可以使用rollback()方法回滚,如果在增删改之后没有commit所有操作都是白搭

操作游标的方法

close():关闭此游标对象
fetchone():得到结果集的下一行
fetchmany([size = cursor.arraysize]):得到结果集的下几行
fetchall():得到结果集中剩下的所有行
excute(sql[, args]):执行一个数据库查询或命令
excutemany(sql, args):执行多个数据库查询或命令

现在上代码

其实现python与mysql的交互就是把mysql语句写在cursor.exexute()构造函数里操作游标,最后再使用commit提交操作

import pymysql
# 连接mysql
# host为数据库的主机IP地址, port为MySQL的默认端口号, user为数据的用户名, password为数据库的登录密码, db为数据库的名称
config = {
    'host': 'localhost',
    'port': 3306,
    'user': 'root',
    'password': '123456',
    'database': 'reptiledata'
}
db = pymysql.connect(**config)
cursor = db.cursor() # 建立游标对象

# -----------------------------------------表操作----------------------------------------------------------------
# 如果存在就删除表没有则新建
cursor.execute("drop table if exists user")

# 新增表
cursor.execute("""create table if not exists user(
                  id int auto_increment primary key,
                  name varchar(5),
                  sex  char(1),
                  id_card  char(18),
                  phone  varchar(14),
                  address  varchar(12),
                  create_time time)""")

# 修改自增长Id,数据库新增的数据会从1000开始但是原来的数据不会改变
cursor.execute('alter table user AUTO_INCREMENT=1000')

# 新增数据库表字段
cursor.execute('alter table user add plus varchar(8)')
# --------------------------插入数据-------------------------------------------------------------------------------
# 批量插入数据
cursor.execute('alter table user drop plus')

# 插入单条数据但因为后面用了db.rollback()回滚,所以此条数据不会被添加
cursor.execute("""insert into user(name, sex, id_card, phone, address)
        values ('李四', '女', '511569845612354879', '10086', '数据不会被添加')""")
db.rollback() 

# 批量插入数据
sql = """insert into user(name, sex, id_card, phone, address)
        values (%s, %s, %s, %s, %s)"""
sql_data = [['张三', '女', '511569845612354879', '10086', '太古里77号'],
            ['李四', '男', '511569845612354879', '10086', '太古里77号'],
            ['王麻子子', '男', '511569845612354879', '10086', '太古里66号'],
            ['张二', '女', '511569845612354879', '10086', '太古里77号'],
            ['李五', '男', '511569845612354879', '10086', '太古里88号'],
            ['王麻子', '女', '511569845612354879', '10086', '太古里99号']]
cursor.executemany(sql, sql_data)

# ----------------------------------------查询数据-----------------------------------------------------------------

# order by 对查询结果进行排序 select 字段1,字段2,字段3 from 表名 order by 字段 desc(降序)||asc(升序)
cursor.execute("select address,id from user order by id desc")
select = cursor.fetchall()
print(select)

# 去重复查询 select distinct 字段 from 表名
cursor.execute("select distinct address from user")
select = cursor.fetchall()
print(select)

# 分页查询 limit select 字段1,字段2 from 表名 limit 初始位置,记录数
cursor.execute("select id, name, sex, id_card from user limit 3,6")
select = cursor.fetchall()
print(select)

# 精准查询 in 只查找括号内的数据; not in 则相反
cursor.execute("select * from user where ID in (1001,1003)")
select = cursor.fetchall()
print(select)

# 精准查询 between and 查找1001-1003范围内的数据;not between and 相反
cursor.execute("select * from user where ID between 1001 and 1003")
select = cursor.fetchall()
print(select)

# 模糊查询 like (% 代表任意字符 _ 代表单个字符);not like相反
cursor.execute("select * from user where name like '_麻%'")
select = cursor.fetchall()
print(select)

# 多条件查询 and 关键字
cursor.execute("select * from user where sex='女' and address='太古里77号'")
select = cursor.fetchall()
print(select)

# 多条件查询 or 关键字 只需满足一个条件
cursor.execute("select * from user where name='王麻子子' or address='太古里77号' ")
select = cursor.fetchall()
print(select)

# ------删除数据和更新数据 or,and,between and,like等关键字可以查询到多条数据然后批量删除或者更新-----------------------------------
# 删除数据
cursor.execute("delete from user where name='王麻子子' or address='太古里77号'")

# 更新数据
cursor.execute("update user set name = '更新' where ID in (1005,1006)")

cursor.close()  # 关闭游标对象
db.commit()  # 提交操作
db.close()  # 关闭数据库

若对你有帮助或喜欢本文请点赞 o( ̄▽ ̄)d
如有不足、需要改善或者还能优化的地方欢迎指出不胜感激,欢迎留言交流  (´▽`ʃ♡ƪ)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值