python基础篇-python操作mysql

本篇对于Python操作MySQL主要使用两种方式:

  • 原生模块 pymsql
  • ORM框架 SQLAchemy

pymysql

下载安装

pip3 install pymysql   #pip3命令的路径:安装路径下的Scripts目录

# 下载 pymysql到本地
# 解压到执行目录
# python2,默认无pip命令
# python3,默认自带pip3命令 python3 -m pip install --upgrade pip 更新pip
#https://pypi.python.org/pypi  模块源

使用操作

1.执行sql语句

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import pymysql
 4
 5 # 创建连接
 6 conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123‘, db=‘t1‘,charset=‘utf8‘)
 7 # 创建游标(创建连接只是打开了数据库,要想取数据需要通过游标来取)
 8 cursor = conn.cursor()
 9
10 # 执行SQL,并返回受收影响行数(即有一个返回值)
11 effect_row = cursor.execute("update hosts set host = ‘1.1.1.2‘")
12 cursor.execute("insert into class(caption) values(‘全栈二班‘)")
13
14 # 执行SQL,并返回受影响行数,插入多行使用executemany
15 #effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])
16 effect_row = cursor.execute("delete from score where sid = 3")
17
18 inp = input("请输入IP地址")
19 cursor.execute("insert into hosts(host) values(%s)",inp)20 21 cursor.execute("select * from student")   #查询的数据从数据库中取出保存在内存中22 result1 = cursor.fetchall()23 print(result1)   #输出查询的结果24 result2 = cursor.fetchone()25 print(result2)  #输出查询的第一条结果26 result3 = cursor.fetchmany(3)27 print(result3)  #输出查询的前n条结果28
22 # 提交,不然无法保存新建或者修改的数据
23 conn.commit()
24
25 # 关闭游标
26 cursor.close()
27 # 关闭连接
28 conn.close()

2.获取查询数据

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import pymysql
 4
 5 conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123‘, db=‘t1‘)
 6 cursor = conn.cursor()
 7 cursor.execute("select * from hosts")
 8
 9 # 获取第一行数据
10 row_1 = cursor.fetchone()
11
12 # 获取前n行数据
13 # row_2 = cursor.fetchmany(3)
14 # 获取所有数据
15 # row_3 = cursor.fetchall()
16
17 conn.commit()
18 cursor.close()
19 conn.close()

注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:

    • cursor.scroll(1,mode=‘relative‘)  # 相对当前位置移动即指针相对当前位置往下走一个,负数表示往上走
    • cursor.scroll(2,mode=‘absolute‘) # 相对绝对位置移动即指针回到第2个位置

3.sql注入

  无需用户名和密码就可以实现对数据库进行插入操作

 1 conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123‘, db=‘t1‘)
 2 #正常应采用以下的方式,不会出现安全问题
 3 cursor.execute(‘select username,password from userinfo where username=%s and password=%s‘,(‘alex‘,123))
 4 result = cursor.fetchone()
 5 print(result)
 6
 7 #字符串拼接会出现安全问题
 8 #可正常执行:
 9 sql = ‘select username,password from userinfo where username="%s" and password="%s"‘
10 sql = sql %(‘alex‘,123)
11 cursor.execute(sql)
12 result = cursor.fetchone()
13 print(result)
14
15 #不能执行
16 sql = ‘select username,password from userinfo where username="%s" and password="%s"‘17 sql = sql %(‘alex‘,1236)
18 cursor.execute(sql)
19 result = cursor.fetchone()
20 print(result)
21
22 #可正常执行:即密码错误也能取到数据
23 sql = ‘select username,password from userinfo where username="%s" and password="%s"‘24 sql = sql %(‘alex‘‘ -- ‘,1236)   #‘select username,password from userinfo where username="alex‘‘ -- " and password="%s"‘  后面的就注释掉   #sql = sql %(‘alex‘‘ or 1=1 -- ‘,1236)  即使不存在用户名也成立即命令也能执行
25 cursor.execute(sql)
26 result = cursor.fetchone()
27 print(result)

4.fetch数据类型

关于默认获取的数据是元祖类型,如果想要获取字典类型的数据,即:

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import pymysql
 4
 5 conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123‘, db=‘t1‘)
 6
 7 # 游标设置为字典类型
 8 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
 9 10
11 result = cursor.fetchone()
12
13 conn.commit()
14 cursor.close()
15 conn.close()

5.获取新创建数据自增ID

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import pymysql
 4
 5 conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123‘, db=‘t1‘)
 6 cursor = conn.cursor()
 7 cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])
 8 conn.commit()
 9 cursor.close()
10 conn.close()
11
12 # 获取最新自增ID
13 new_id = cursor.lastrowid

原文地址:https://www.cnblogs.com/lriwu/p/8464910.html

时间: 2024-08-25 17:58:32

python基础篇-python操作mysql的相关文章

老王python基础篇--python, 视频, 教程, 视频教程, 基础

老王python基础篇 基础篇11-python基本数据结构-元组和集合.rar 基础篇19-python语句与数据结构应用.rar 基础篇21-文本操作应用.rar 基础篇3-虚拟机安装xubuntu开发环境.rar 基础篇17-python语句1.2.rar 基础篇10-python基本数据结构-列表应用.rar 基础篇9-python基本数据结构-列表.rar 基础篇5-python基本数据类型讲解1.1.rar 基础篇18-基础篇综合习题.rar 基础篇8-python基本数据类型习题解

Python基础篇-Python基础语法

Python基础语法 为什么学习python Python的安装 rpm -q python uname -r python -V yum -y install python-pip pip install ipython         支持 2.7 pip install ipython==1.2.1                支持 2.6

Python基础篇-Python基础进阶

1.1 函数定义.mp4

Python基础篇(八)

key words:私有变量,类静态变量,生成器,导入Python模块,r查看模块可以使用的函数,查看帮助信息,启动外部程序,集合,堆,时间模块,random模块,shelve模块,文件读取等 >>> class Rectangle: ...     def __init__(self): ...         self.__width = 0 ...         self.__height = 0 ...     def setSize(self,width,height): .

Python基础篇(五)

bool用于判断布尔值的结果是True还是False >>> bool("a") True >>> bool(3) True >>> bool("") False >>> bool(0) False Python中的elif类似于Java中的elseif >>> number = (int)(input("input a number: ")) input

工程脚本插件方案 - c集成Python基础篇

工程脚本插件方案 - c集成Python基础篇 序: 为什么要集成脚本,怎么在工程中集成Python脚本. 在做比较大型的工程时,一般都会分核心层和业务层.核心层要求实现高效和稳定的基础功能,并提供调用接口供业务层调用的一种标准的框架划分.在实际中根据需求会拆分的更细. 外部的表现形式就是一个核心动态库,带着一堆业务业务动态库.通过一个调度程序把这些链接起来,外加一堆配置文件,就形成一个完成的项目. 这种模式在一个团队开发中,工作职责比较容易划分.制定API接口后,开发工作基本可以并行实现,包括

python基础篇(二)

python基础篇(二) if:else,缩进和循环控制 A:if的基础格式和缩进 B:循环判断 C:range()函数和len()函数 D:break,contiue和pass语句 for,while循环 函数基础 A:函数的定义和返回值 B:返回值的三种情况 C:函数的注释 函数的进阶(命名空间和作用域) A:内置命名空间 B:全局命名空间 C:局部命名空间 D:全局作用域 E:局部作用域 F:函数的嵌套和作用域链. G:函数名的本质 闭包 ?一:if:else和缩进 A:if的基础格式和缩

python基础篇(五)

python基础篇(五) 算法初识 什么是算法 二分查找算法 ?一:算法初识 A:什么是算法 根据人们长时间接触以来,发现计算机在计算某些一些简单的数据的时候会表现的比较笨拙,而这些数据的计算会消耗大量计算机资源,而且耗时,这个时候就有人对这类计算编写了一些策略,这些策略就是算法.这些策略会加快数据计算时间,大大减少计算机的资源消耗. 在长时间人们编写代码的工作中,一些优秀的算法就被流传下来,但是不是所有的算法都能实现目的一步到位的工作,它只能减少你的代码,提高工作效率,随着知识的不断积累,你会

python基础篇

python基础篇 变量命名 >>> name_value='freddy' 1 >>> name_value=freddy 2 Traceback (most recent call last): 3 File "<stdin>", line 1, in <module> 4 NameError: name 'freddy' is not defined **变量的值如果是字符串必须要加引号,否则定义变量会报错 (因为他把变