Python3连接MySQL

介绍

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。

Django中也可以使用PyMySQL连接MySQL数据库。

安装模块

pip3 install pymysql

连接数据库

基本使用

# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
# 定义要执行的SQL语句
sql = """
CREATE TABLE USER1 (
id INT auto_increment PRIMARY KEY ,
name CHAR(10) NOT NULL UNIQUE,
age TINYINT NOT NULL
)ENGINE=innodb DEFAULT CHARSET=utf8;
"""
# 执行SQL语句
cursor.execute(sql)
# 关闭光标对象
cursor.close()
# 关闭数据库连接
conn.close()

execute()之sql注入

注意:符号--会注释掉它之后的sql,正确的语法:--后至少有一个任意字符

根本原理:就根据程序的字符串拼接name='%s',我们输入一个xxx' -- haha,用我们输入的xxx加'在程序中拼接成一个判断条件name='xxx' -- haha'

最后那一个空格,在一条sql语句中如果遇到select * from t1 where id > 3 -- and name='egon';则--之后的条件被注释掉了

#1、sql注入之:用户存在,绕过密码
egon' -- 任意字符 #2、sql注入之:用户不存在,绕过用户与密码
xxx' or 1=1 -- 任意字符
import pymysql
# 获取用户输入
name = input("用户名>>:")
pwd = input("密码>>:") # 校验用户输入的用户名和密码是否正确
# 去数据库里取数据做判断
# 1. 连上数据库
conn = pymysql.connect(host="localhost",database="day60", user="root", password="", charset="utf8") # 不是utf-8
# 光有链接还不行,需要获取光标,让我能够输入SQL语句并执行
cursor = conn.cursor()
# 2. 执行SQL语句 --> select * from userinfo where name=name and pwd=pwd
sql = "select * from userinfo WHERE name='%s' and pwd='%s';" % (name, pwd)
print(sql)
ret = cursor.execute(sql) # 获取影响的行数
# 关闭光标和连接
cursor.close()
conn.close()
if ret:
print("登陆成功")
else:
print("登录失败")

解决mysql的注入问题

# 原来是我们对sql进行字符串拼接
# sql="select * from userinfo where name='%s' and password='%s'" %(user,pwd)
# print(sql)
# res=cursor.execute(sql) #改写为(execute帮我们做字符串拼接,我们无需且一定不能再为%s加引号了)
sql="select * from userinfo where name=%s and password=%s" #!!!注意%s需要去掉引号,因为pymysql会自动为我们加上
res=cursor.execute(sql,[user,pwd]) #pymysql模块自动帮我们解决sql注入的问题,只要我们按照pymysql的规矩来。
import pymysql
# 获取用户输入
name = input("用户名>>:")
pwd = input("密码>>:") # 校验用户输入的用户名和密码是否正确
# 去数据库里取数据做判断
# 1. 连上数据库
conn = pymysql.connect(host="localhost",database="day60", user="root", password="", charset="utf8") # 不是utf-8
# 光有链接还不行,需要获取光标,让我能够输入SQL语句并执行
cursor = conn.cursor()
# 2. 执行SQL语句 --> select * from userinfo where name=name and pwd=pwd
sql = "select * from userinfo WHERE name=%s and pwd=%s;"
print(sql) # 解决:让pymysql拼接字符串
ret = cursor.execute(sql,[name,pwd]) # 获取影响的行数
# 关闭光标和连接
cursor.close()
conn.close()
if ret:
print("登陆成功")
else:
print("登录失败")

增删改查操作

import pymysql

#  连接
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”) # 获取光标
cursor = conn.cursor() # 写sql语句
sql = "insert into userinfo(name,pwd) VALUE (%s,%s);" username = "dandan"
password = ""
# 执行sql语句
cursor.execute(sql,(username,password))
conn.commit() # 把修改提交到数据库 (提交事务)
cursor.close()
conn.close()

插入数据失败回滚

# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
username = "lishi"
password = "1220"
try: # 执行SQL语句  cursor.execute(sql, [username, age]) # 提交事务  conn.commit() except Exception as e: # 有异常,回滚事务  conn.rollback() cursor.close() conn.close()

获取插入数据的ID(关联操作时会用到)

# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
username = "Alex"
age = 18
try:
# 执行SQL语句
cursor.execute(sql, [username, age])
# 提交事务
conn.commit()
# 提交之后,获取刚插入的数据的ID
last_id = cursor.lastrowid
except Exception as e:
# 有异常,回滚事务
conn.rollback()
cursor.close()
conn.close()

批量执行:用executemany()插入多条信息

# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
data = [("lishi", 18), ("lili", 20), ("dandna", 21)]
try:
# 批量执行多条插入SQL语句
cursor.executemany(sql, data)
# 提交事务
conn.commit()
except Exception as e:
# 有异常,回滚事务
conn.rollback()
cursor.close()
conn.close()

# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
sql = "DELETE FROM USER1 WHERE id=%s;"
try:
cursor.execute(sql, [4])
# 提交事务
conn.commit()
except Exception as e:
# 有异常,回滚事务
conn.rollback()
cursor.close()
conn.close()

# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
# 修改数据的SQL语句
sql = "UPDATE USER1 SET age=%s WHERE name=%s;"
username = "Alex"
age = 80
try:
# 执行SQL语句
cursor.execute(sql, [age, username])
# 提交事务
conn.commit()
except Exception as e:
# 有异常,回滚事务
conn.rollback()
cursor.close()
conn.close()

查fetchone、fetchmany、fetchall

查询单条数据

# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
# 查询数据的SQL语句
sql = "SELECT id,name,age from USER1 WHERE id=1;"
# 执行SQL语句
cursor.execute(sql)
# 获取单条查询数据
ret = cursor.fetchone()
cursor.close()
conn.close()
# 打印下查询结果
print(ret)

查询多条数据

# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
# 查询数据的SQL语句
sql = "SELECT id,name,age from USER1;"
# 执行SQL语句
cursor.execute(sql)
# 获取多条查询数据
ret = cursor.fetchall()
cursor.close()
conn.close()
# 打印下查询结果
print(ret)

进阶用法

# 可以获取指定数量的数据
cursor.fetctmany(3)
# 光标按绝对位置移动1
cursor.scroll(1, mode="absolute")
# 光标按照相对位置(当前位置)移动1
cursor.scroll(1, mode="relative")

pymysql 模块的更多相关文章

  1. Python中操作mysql的pymysql模块详解

    Python中操作mysql的pymysql模块详解 前言 pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同.但目前pymysql支持python3.x而后者不支持 ...

  2. python实战第一天-pymysql模块并练习

    操作系统 Ubuntu 15.10 IDE & editor JetBrains PyCharm 5.0.2 ipython3 Python版本 python-3.4.3 安装pymysql模 ...

  3. pymysql 模块介绍

    pymysql模块是python与mysql进行交互的一个模块. pymysql模块的安装: pymysql模块的用法: import pymysql user=input('user>> ...

  4. Mysql(六):数据备份、pymysql模块

    一 IDE工具介绍 生产环境还是推荐使用mysql命令行,但为了方便我们测试,可以使用IDE工具 下载链接:https://pan.baidu.com/s/1bpo5mqj 掌握: #1. 测试+链接 ...

  5. python如何使用pymysql模块

    Python 3.x 操作MySQL的pymysql模块详解 前言pymysql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同.但目前pymysql支持python3.x而M ...

  6. MySQL之pymysql模块

    MySQL之pymysql模块   import pymysql #s链接数据库 conn = pymysql.connect( host = '127.0.0.1', #被连接数据库的ip地址 po ...

  7. PyMySQL模块的使用

    PyMySQL介绍 PyMySQL是在Python3.x版本中用于连接MySQL服务器的一个库,Python2系列中则使用mysqldb.Django中也可以使用PyMySQL连接MySQL数据库. ...

  8. MySQL学习12 - pymysql模块的使用

    一.pymysql的下载和使用 1.pymysql模块的下载 2.pymysql的使用 二.execute()之sql注入 三.增.删.改:conn.commit() 四.查:fetchone.fet ...

  9. 数据库入门-pymysql模块的使用

    一.pymysql模块安装 由于本人的Python版本为python3.7,所以用pymysql来连接数据库(mysqldb不支持python3.x) 方法一: #在cmd输入 pip3 instal ...

  10. Python连接MySQL数据库之pymysql模块使用

    安装PyMySQL pip install pymysql PyMySQL介绍 PyMySQL是在python3.x版本中用于连接MySQL服务器的一个库,2中则使用mysqldb. Django中也 ...

随机推荐

  1. 微信小程序组件checkbox

    表单组件checkbox:官方文档 Demo Code: JS Page({ data:{ items:[ {name: 'USA', value: '美国'}, {name: 'CHN', valu ...

  2. python之路 线程、进程、协程、队列、python-memcache、python-redis

    一.线程 Threading用于提供线程相关的操作,线程是应用程序中工作的最小单元. #!/usr/bin/env python # -*- coding:utf-8 -*- import threa ...

  3. PolyBase--整合SQLServer和Hadoop

    我们一直强调,大数据和传统的关系数据库并不对立,未来公司的的业务将会是大数据和关系型数据库的整合.微软的PolyBase打响了SQL Server和Hadoop整合的第一枪. 在2012年度的SQL ...

  4. 20145235李涛《网络对抗》Exp7 网络欺诈技术防范

    基础问题回答 通常在什么场景下容易受到DNS spoof攻击? 使用未知的公共wifi或者在不安全的局域网下容易受到DNS spoof攻击. 在日常生活工作中如何防范以上两攻击方法? 首先要提高防范意 ...

  5. angularjs Dom方式访问疑似可以访问ifame结构项目

    一.定位需要访问控制器元素 var currObj = document.querySelector('[ng-controller="munuListCtrl"]'); 或者 v ...

  6. Spring注解(事务)

    spring操作数据库 jdbc <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> & ...

  7. pbs "ll: command not found"

    可以用  ls -ltr   替代 ll

  8. Redis 后台运行

    编辑配置文件 vim {redis_home}/redis.conf 修改daemonize  (默认为no,修改为yes) 启动redis{redis_home}/src/redis-server ...

  9. eclipse中设置新建jsp文件的编码格式

    每次新建jsp文件时,默认都是ISO-8859-1,每次涉及有中文的时候都得改成UTF-8,这就很麻烦了. 解决的方法就是,设置新建jsp文件的编码格式. 解决方法 结果 或者更改它的encoding

  10. Dev控件-gridview的属性说明

    说明 Options OptionsBehavior 视图的行为选项 AllowIncrementalSearch 允许用户通过输入想得到的列值来定位行 AllowPartialRedrawOnScr ...