pymysql:python操作mysql

安装pymysql

>: pip3 install pymysql

增删改查

# 选取操作的模块 pymysql

# pymysql连接数据库的必要参数:主机、端口、用户名、密码、数据库

# 注:pymysql不能提供创建数据库的服务,数据库要提前创建

import pymysql

# 1)建立数据库连接对象 conn

# 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 执行

创建表

# 创建表

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()

sql3 = 'delete from t1 where id=%s'

cursor.execute(sql3, 4)

conn.commit()

sql4 = 'update t1 set y=666 where id=2'

cursor.execute(sql4)

conn.commit()

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注入问题和解决

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('登录失败')

"""

# 知道用户名时

# 输入用户时:

# 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"

解决注入问题

sql = 'select * from user where name=%s and password=%s'

row = cursor.execute(sql, (usr, pwd))

if row:

print('登录成功')

else:

print('登录失败')

索引

索引就是 键 - key

1)键 是添加给数据库表的 字段 的

2)给表创建 键 后,该表不仅会形参 表结构、表数据,还有 键的B+结构图

3)键的结构图是需要维护的,在数据完成增、删、改操作时,只要影响到有键的字段,结构图都要维护一次

所以创建键后一定会降低 增、删、改 的效率

4)键可以极大的加快查询速度(开发需求中,几乎业务都和查有关系)

5)建立键的方式:主键、外键、唯一键、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)###############索引,对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)

python豆瓣mysql_python操作mysql相关推荐

  1. python app mysql_Python 操作 MySQL 的5种方式

    不管你是做数据分析,还是网络爬虫,Web 开发.亦或是机器学习,你都离不开要和数据库打交道,而 MySQL 又是最流行的一种数据库,这篇文章介绍 Python 操作 MySQL 的 5 种方式,你可以 ...

  2. python启动mysql_Python操作MySQL

    安装PyMySQL python中连接mysql的客户端主要有mysqldb.mysql-connector.pymysql三种.虽说性能上面各有差别,但是主流市场还是以操作便捷.使用简单为选择条件. ...

  3. python logging mysql_Python 操作 MySQL 的正确姿势

    欢迎大家关注腾讯云技术社区-博客园官方主页,我们将持续在博客园为大家推荐技术精品文章哦~ 作者:邵建永 使用Python进行MySQL的库主要有三个,Python-MySQL(更熟悉的名字可能是MyS ...

  4. Python模块MySQLdb操作mysql出现2019错误:Can't initialize character set utf-8

    我使用python的MySQLdb模块实现了一个mysql client, 在测试时,出现了如下错误 Python模块MySQLdb操作mysql出现2019错误:Can't initialize c ...

  5. python豆瓣mysql_python爬虫获取豆瓣电影——Python操作MySQL存储数据

    30 May 2015 爬虫抓到的数据需要存储到MySQL中,所以我们需要熟悉下使用Python操作MySQL数据库.首先你的机器上要安装MySQLdb,MySQLdb是用于Python连接Mysql ...

  6. python 操作mysql_Python 操作MySQL

    我的Python环境: Python 2.7.14 |Anaconda, Inc.| (default, Oct 16 2017, 17:29:19) [GCC 7.2.0] on linux2 Ty ...

  7. python数据库mysql_python数据库(mysql)操作

    一.软件环境 python环境默认安装了sqlite3,如果需要使用sqlite3我们直接可以在python代码模块的顶部使用import sqlite3来导入该模块.本篇文章我是记录了python操 ...

  8. python增删改查mysql_Python操作MySQL(增删改查)

    Python操作MySQL数据库方法.方式总结 import pandas as pd import pymysql import sqlalchemy from sqlalchemy import ...

  9. python加mysql加界面用代码写_python加mysql_python操作mysql

    python操作mysql可用的第三方库有MySQLdb,pymysql等. 下面主要讲解MySQLdb: 1.用pip安装mysqlclient库,连接python和mysql pip3 insta ...

最新文章

  1. lsm tree java_LSM-tree 基本原理及应用
  2. 用python做问答测试_测试用户输入Python
  3. 机器人学习--定位、建图、SLAM(声呐、激光等扫描束方案)的发展史
  4. 关于JAP FetchType.LAZY(hibernate实现)的理解
  5. 推动Windows的限制:句柄
  6. JDK1.5中的线程池(java.util.concurrent.ThreadPoolExecut
  7. oracle aia,[zz] What Are Oracle AIA, PIP and How Do They Work?
  8. oracle进行日志切换,Oracle存档日志切换案例操作
  9. 为系统安装盘集成Server Pack补丁包
  10. 《云数据中心构建实战:核心技术、运维管理、安全与高可用》——2.4 云计算的发展历程与未来趋势...
  11. linux 分区100g整数,硬盘分区 整G 整数 法(从1g到200g最精确的整数分区)(转)...
  12. PHP语言面对对象编程之继承
  13. 【Android】Doze模式识别与检测
  14. tornado 源码分析 waker
  15. 手机屏幕显示正常但是触摸有一部分出问题,是内屏坏了吗?保修期内手机该不该走官方售后?
  16. 动物叫声合集v1.0支持25种动物叫声模拟
  17. 互联网摸鱼日报(2022-12-23)
  18. IP、域名和端口号之间的联系
  19. JSP PreparedStatement.setDate
  20. jmeter构造测试数据

热门文章

  1. 曝光:一位来自微软公司的粉丝 写给我的信
  2. 12月12日习题答案大剖析!再接再厉
  3. eclipse中的java包awt_Eclipse中打包java程序
  4. opengl实现经纹理映射的旋转立方体_《图形编程技术学习》(五十三)环境映射...
  5. Gaze Estimation笔记——data normalization
  6. P53:进化了8亿年的抑癌基因
  7. 花器官身份基因与靶基因间的调控进化情况
  8. 又双叒叕一个软件安装方法
  9. USACO详细介绍 全球中小学生均可参加
  10. BCrypt加密怎么存入数据库_dns污染怎么解决