pymysql 基操全套

pymysql:python操作mysql

什么是pymysql?

pymysql是一个python连接操作mysql数据的一个模块。没有他我们就不能和mysql连接所以安装...

安装
>: pip3 install pymysql
什么是Cursor游标?

游标(Cursor)是处理数据的一种方法,为了查看或者处理结果集中的数据,游标提供了在结果集中一次一行或者多行前进或向后浏览数据的能力。

设置pymysql.cursors.DictCursor,查询的结果是字典,key是表的字段

语法

​ conn.commit() 提交
​ conn.cursor(pymysql.cursors.DictCursor)设置游标对象
​ cursor.execute(sql) 执行语sql语句
​ conn.cursor(pymysql.cursors.DictCursor)设置DictCursor
​ 特殊fetch 取
​ 查询需要通过fetchone操作
​ fetchmany(个数)
​ fetchall()全部

增删改查

增删改查之前需要自己创建数据库

# 选取操作的模块 pymysql

# pymysql连接数据库的必要参数:主机、端口、用户名、密码、数据库
# 注:pymysql不能提供创建数据库的服务,数据库要提前创建
import pymysql
from pymysql.cursors import DictCursor
# 1)建立数据库连接对象 conn  就可以创建sql的游标对象
# 2)通过 conn 创建操作sql的 游标对象理:结果集中的数据,游标提供了在结果集中一次一行或者多行前进或向后浏览数据的能力。
# 3)编写sql交给 cursor 执行
# 4)如果是查询,通过 cursor光标对象 获取结果  
# 5)操作完毕,端口操作与连接


# 1)建立数据库连接对象 conn
conn = pymysql.connect(user='root', passwd='root', database='oldboy')
# conn = pymysql.connect(user='root', passwd='root', database='oldboy', autocommit=True)

# 2)通过 conn 创建操作sql的 游标对象
# 注:游标不设置参数,查询的结果就是数据元组,数据没有标识性
# 设置pymysql.cursors.DictCursor,查询的结果是字典,key是表的字段
cursor = conn.cursor(pymysql.cursors.DictCursor)

# 3)编写sql交给 cursor 执行

sql5 = 'select * from t1'
row = cursor.execute(sql5)  # 返回值是执行语句的行数
print(row)
创建表
# 创建表
sql1 = 'create table t1(id int, x int, y int)'
cursor.execute(sql1)
sql2 = 'insert into t1 values(%s, %s, %s)'

# 增1
cursor.execute(sql2, (1, 10, 100))
cursor.execute(sql2, (2, 20, 200))
# 重点:在创建conn对象时,不设置autocommit,默认开启事务,增删改操作不会直接映射到数据库中,
# 需要执行 conn.commit() 动作
conn.commit()

# 增多
cursor.executemany(sql2, [(3, 30, 300), (4, 40, 400)])
conn.commit()
delete删
sql3 = 'delete from t1 where id=%s'
cursor.execute(sql3, 4)
conn.commit()
update改

sql4 = 'update t1 set y=666 where id=2'
cursor.execute(sql4)
conn.commit()
fetch取

sql5 = 'select * from t1'
row = cursor.execute(sql5)  # 返回值是执行语句受影响的行数
print(row)

# 4)如果是查询表内记录,通过 cursor对象 获取结果
# fetchone() 偏移一条取出,fetchmany(n) 偏移n条取出,fetchall() 偏移剩余全部
r1 = cursor.fetchone()
print(r1)
r2 = cursor.fetchone()
print(r2)
r3 = cursor.fetchmany(1)
print(r3)
r4 = cursor.fetchall()
print(r4)
# 5)操作完毕,端口操作断开连接
cursor.close()
conn.close()

游标操作

import pymysql
from pymysql.cursors import DictCursor

# 1)建立数据库连接对象 conn
conn = pymysql.connect(user='root', passwd='root', db='oldboy')
# 2)通过 conn 创建操作sql的 游标对象
cursor = conn.cursor(DictCursor)
# 3)编写sql交给 cursor 执行
sql = 'select * from t1'
# 4)如果是查询,通过 cursor对象 获取结果
row = cursor.execute(sql)
if row:
    r1 = cursor.fetchmany(2)
    print(r1)

    # 操作游标
    # cursor.scroll(0, 'absolute')  # absolute绝对偏移,游标重置,从头开始偏移
    cursor.scroll(-2, 'relative')  # relative相对偏移,游标在当前位置进行左右偏移

    r2 = cursor.fetchone()
    print(r2)

# 5)操作完毕,端口操作与连接
cursor.close()
conn.close()

pymysql事务

​ 要保证他的安全性
​ 逻辑要写好

如果是转账的话必须检测两个都成功才可以提交数据库

import pymysql
from pymysql.cursors import DictCursor
conn = pymysql.connect(user='root', passwd='root', db='oldboy')
cursor = conn.cursor(DictCursor)

try:
    sql = 'create table t2(id int, name char(4), money int)'
    row = cursor.execute(sql)
    print(row)
except:
    print('表已创建')
    pass

# 空表才插入
row = cursor.execute('select * from t2')
if not row:
    sql = 'insert into t2 values(%s,%s,%s)'
    row = cursor.executemany(sql, [(1, 'tom', 10), (2, 'Bob', 10)])
    conn.commit()


# 可能会出现异常的sql
"""
try:
    sql1 = 'update t2 set money=money-1 where name="tom"'
    cursor.execute(sql1)
    sql2 = 'update t2 set moneys=money+1 where name="Bob"'
    cursor.execute(sql2)
except:
    print('转账执行异常')
    conn.rollback()
else:
    print('转账成功')
    conn.commit()
"""

try:
    sql1 = 'update t2 set money=money-1 where name="tom"'
    r1 = cursor.execute(sql1)
    sql2 = 'update t2 set money=money+1 where name="ruakei"'  # 转入的人不存在
    r2 = cursor.execute(sql2)
except:
    print('转账执行异常')
    conn.rollback()
else:
    print('转账没有异常')
    if r1 == 1 and r2 == 1:
        print('转账成功')
        conn.commit()
    else:
        conn.rollback()

sql注入

什么是sql注入?

目的最终达到欺骗服务器执行恶意的sql命令.

是什么:

sql注入,就是通过sql命令插入到web表单提交或输入域名或者页面请求的查询字符串,

如何实现

前提自己拼接参数用占位符
知道用户名
利用注释和"
都不知道
利用or的特性
注意
自己拼接参数的时候一定有sql注入,将数据的占位填充给pymysql

代码详解


import pymysql
from pymysql.cursors import DictCursor
conn = pymysql.connect(user='root', passwd='root', db='oldboy')
cursor = conn.cursor(DictCursor)

try:
    sql = 'create table user(id int, name char(4), password char(6))'
    row = cursor.execute(sql)
    print(row)
except:
    print('表已创建')
    pass

# 空表才插入
row = cursor.execute('select * from user')
if not row:
    sql = 'insert into user values(%s,%s,%s)'
    row = cursor.executemany(sql, [(1, 'tom', '123'), (2, 'bob', 'abc')])
    conn.commit()



# 用户登录
usr = input('usr: ')
pwd = input('pwd: ')

# 自己拼接参数一定有sql注入,将数据的占位填充交给pymysql

"""
sql = 'select * from user where name="%s" and password="%s"' % (usr, pwd)
row = cursor.execute(sql)
if row:
    print('登录成功')
else:
    print('登录失败')
"""
sql = 'select * from user where name=%s and password=%s'
row = cursor.execute(sql, (usr, pwd))
if row:
    print('登录成功')
else:
    print('登录失败')


# 知道用户名时
# 输入用户时:
#   tom => select * from user where name="tom" and password="%s"
#   tom" # => select * from user where name="tom" #" and password="%s"

# 不自定义用户名时
#   " or 1=1 # => select * from user where name="" or 1=1 #" and password="%s"

索引

索引就是 键 - key

键是用来干嘛的

1)键 是添加给数据库表的 字段 的
2)给表创建 键 后,该表不仅会形参 表结构、表数据,还有 键的B+结构图

缺点

1)键的结构图是需要维护的,在数据完成增、删、改操作时,只要影响到有键的字段,结构图都要维护一次
所以创建键后一定会降低 增、删、改 的效率
2)键可以极大的加快查询速度(开发需求中,几乎业务都和查有关系)

建立方式

建立键的方式:主键、外键、唯一键、index

代码详解



import pymysql
from pymysql.cursors import DictCursor
conn = pymysql.connect(user='root', passwd='root', db='oldboy')
cursor = conn.cursor(DictCursor)

# 创建两张表
# sql1 = """create table a1(
#     id int primary key auto_increment,
#     x int,
#     y int
# )"""
# cursor.execute(sql1)
# sql2 = """create table a2(
#     id int primary key auto_increment,
#     x int,
#     y int,
#     index(x)
# )"""
# cursor.execute(sql2)

# 每个表插入5000条数据
# import random
# for i in range(1, 5001):
#     x = i
#     y = random.randint(1, 5000)
#     cursor.execute('insert into a1(x, y) values(%s, %s)', (x, y))
#     cursor.execute('insert into a2(x, y) values(%s, %s)', (x, y))
#
# conn.commit()

import time
# a1的x、a1的id、a2的x
b_time = time.time()
sql = 'select * from a1 where id=4975'
cursor.execute(sql)
e_time = time.time()
print(e_time - b_time)

b_time = time.time()
sql = 'select * from a1 where x=4975'
cursor.execute(sql)
e_time = time.time()
print(e_time - b_time)

b_time = time.time()
sql = 'select * from a2 where x=4975'
cursor.execute(sql)
e_time = time.time()
print(e_time - b_time)

转载于:https://www.cnblogs.com/jhpy/p/11600891.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
05-29
`pymysql` 是 Python 编程语言下的一个第三方模块,用于连接 MySQL 数据库。它提供了一组简单而强大的 API,使 Python 开发人员可以轻松地与 MySQL 数据库进行交互。以下是 `pymysql` 的使用示例: ```python import pymysql # 连接数据库 conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='test') # 创建游标对象 cursor = conn.cursor() # 定义查询语句 query = "SELECT * FROM users WHERE username = 'admin'" # 执行查询 cursor.execute(query) # 获取查询结果 result = cursor.fetchall() # 关闭游标和连接 cursor.close() conn.close() # 输出查询结果 print(result) ``` 在上述示例中,我们首先使用 `pymysql.connect()` 方法连接 MySQL 数据库,其中需要指定数据库服务器的地址、端口、用户名和密码等信息。然后,我们使用 `cursor.execute()` 方法执行查询语句,并使用 `cursor.fetchall()` 方法获取查询结果。最后,我们关闭游标和连接,以释放资源。 除了执行查询语句之外,`pymysql` 还提供了一系列的方法,用于执行插入、更新、删除等操作,例如: ```python # 定义插入语句 insert_query = "INSERT INTO users (username, password) VALUES ('admin', '123456')" # 执行插入操作 cursor.execute(insert_query) # 提交事务 conn.commit() ``` 在上述示例中,我们使用 `cursor.execute()` 方法执行插入语句,并使用 `conn.commit()` 方法提交事务,以保存修改。 综上所述,`pymysql` 是一种方便、快捷、灵活的 Python MySQL 数据库连接模块,它可以帮助 Python 开发人员轻松地与 MySQL 数据库进行交互。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值