python中pymysql模块操作与使用


pymysql模块使用————(实操)


该软件包包含一个纯Python MySQL客户端库。PyMySQL的目标是成为MySQLdb的替代品,并在CPython,PyPy和IronPython上工作。

注:PyMySQL不支持低级别的API _mysql提供了像data_seek, store_resultuse_result。您应该使用PEP 249中定义的高级API 。但是支持一些API,如自动提交ping,因为PEP 249不包含他们的用例。

要求

  • Python - 以下之一:

  • MySQL服务器 - 以下之一:

安装

Package上传到PyPI

你也可以用pip安装它:

pip3 install pymysql

安装完成之后即可使用了。我们先看看官方的示例:

一.创建一个SQL表

  1. CREATE TABLE `users` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `email` varchar(255) COLLATE utf8_bin NOT NULL,
        `password` varchar(255) COLLATE utf8_bin NOT NULL,
        PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_binAUTO_INCREMENT=1 ;

二.python使用实例:

import pymysql.cursors

# 连接到数据库
connection = pymysql.connect(host='localhost',
                             user='root',
                             password='123',
                             db='books',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # 插入新的数据
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('[email protected]', 'very-secret'))

    # 默认情况下,连接不是自动提交。所以你必须自行保存好
    connection.commit()

    with connection.cursor() as cursor:
        # 读取单个记录
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('[email protected]',))
        result = cursor.fetchone()
        print(result)
finally:
    connection.close()

执行后的结果:

blob.png

说明:这里是以字典为返回结果


一、学习实例操作

#实例一:实现:使用Python实现用户登录,如果用户存在则登录成功(假设该用户已在数据库中)
import pymysql

user = input('请输入用户名:')
pwd = input('请输入密码:')

#1.连接
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='123',
    db = 'dbtest',
    charset='utf8'
)
#2.创建游标
cursor = conn.cursor()
###注意%s需要加引号
sql = "select * from db2 where username = '{}' and password='{}' ".format(user,pwd)
print(sql)

#3.执行sql语句
cursor.execute(sql)
result=cursor.execute(sql) #执行sql语句,返回sql查询成功的记录数目
print(result)

#4.关闭连接,游标和连接都要关闭
cursor.close()
conn.close()

if result:
    print('登录成功!')
else:
    print('登录失败!')

执行后的结果:

blob.png


二、execute()之sql注入

这里只截图演示三种SQL注入示例截图

1

blob.png

2

blob.png

3

blob.png

解决方法: 

# 原来是我们对sql进行字符串拼接
# sql="select * from userinfo where name='%s' and password='%s'" %(username,pwd)
# print(sql)
# result=cursor.execute(sql)

#改写为(execute帮我们做字符串拼接,我们无需且一定不能再为%s加引号了)
sql="select * from userinfo where name=%s and password=%s" #!!!注意%s需要去掉引号,因为pymysql会自动为我们加上
result=cursor.execute(sql,[user,pwd]) #pymysql模块自动帮我们解决sql注入的问题,只要我们按照pymysql的规矩来。


三、增、删、改:conn.commit()

commit()方法:在数据库里增,删,改的时候。必须要进行提交,否则插入的时候数据不生效

import pymysql

username = input('请输入用户名:')
pwd = input('请输入密码:')

#1.连接
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='123',
    db='dbtest',
    charset='utf8'
)

#2.创建游标
cursor = conn.cursor()

#操作
#增
# sql = "insert into db2(username,password) values (%s,%s)"
#
# effect_row = cursor.execute(sql,(username,pwd))
# #同时插入多条数据
# cursor.executemany(sql,[('lisi','110'),('wangwu','119')])
# print(effect_row)

#改
# sql = "update db2 set username = %s where  id = 2"
# effect_row=cursor.execute(sql,username)
# print(effect_row)

#删
# sql = "delete from db2 where id =n 2"
# effect_row = cursor.execute(sql,username)
# print(effect_row)


#一定记得commit
conn.commit()

# 4.关闭游标
cursor.close()


四、查:fetchone、fetchmany、fetchall

fetchone():获取下一行数据,第一次为首行;
fetchall():获取所有行数据源
fetchmany(4):获取4行数据


使用fetchone()

import pymysql

#1.连接
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password ='123',
    db='dbtest',
    charset='utf8'
)

#2.创建游标
cursor = conn.cursor()

sql = 'select * from db2'
cursor.execute(sql)

#3.查询数据
row = cursor.fetchone()
print(row)

#查询第二行数据
row = cursor.fetchone()
print(row)

#4.关闭游标
cursor.close()

#5.关闭连接
conn.close()

执行后输出的结果:

blob.png


使用fetchall()

import pymysql

#1.连接
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='123',
    db = 'dbtest',
    charset='utf8'
)

#2.创建游标
cursor = conn.cursor()

sql = 'select * from db2'
cursor.execute(sql)

#3.获取所有的数据
rows = cursor.fetchall()
print(rows)

#4.关闭游标
cursor.close()

#5.关闭连接
conn.close()

执行后输出结果:

blob.png


使用fetchall()

import pymysql

#1.连接
conn = pymysql.connect(
    host = 'localhost',
    port=3306,
    user = 'root',
    password = '123',
    db = 'dbtest',
    charset = 'utf8'
)

#2.创建游标
cursor = conn.cursor()

sql = 'select * from db2'
cursor.execute(sql)

#3.获取数据
rows = cursor.fetchall()
print(rows)

#4.关闭游标
cursor.close()

#5.关闭连接
conn.close()

执行输出结果:

blob.png

默认情况下,我们获取到的返回值是元祖,只能看到每行的数据,却不知道每一列表的是什么,这个时候可以使用以下方式来返回字典,每一行的数据都会生成一个字典:

cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  #在实例化的时候,将属性cursor设置为pymysql.cursors.DictCursor

在fetchone示例中,在获取数据的时候,可以理解开始的时候,有一个行指针指着第一行的上方,获取一行,它就向下移动一行,所以当行指针到最后一行的时候,就不能在获取到行的内容,所以我们可以使用如下方法来移动行指针:

cursor.scroll(1,mode='relative')  #相对当前位置移动
cursor.scroll(2,mode='absolute')  #相对绝对位置移动
第一个值为移动的行动,整数为向下移动,负数为向下移动,mode指定了是相对当前位置移动,还是相对于行首移动

用户登录实例二:

import pymysql

#1.连接
conn = pymysql.connect(
    host = 'localhost',
    port = 3306,
    user = 'root',
    password = '123',
    db = 'dbtest',
    charset = 'utf8'
)

#2.创建游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
sql = 'select * from db2'
cursor.execute(sql)

#3.查询数据
# 查询第一行的数据

row = cursor.fetchone()
print(row)

# 查询第二行数据
row = cursor.fetchone()
print(row)

cursor.scroll(-1,mode='relative') #设置之后,光标相对当前位置往前移动了一行,所以打印的结果为第二行的数据
row = cursor.fetchone()
print(row)

cursor.scroll(-1,mode='relative') #设置之后,光标相对于行首没有任何,所以打印的结果为第一行数据
row = cursor.fetchone()
print(row)

#4.关闭游标
cursor.close()

#5.关闭连接
conn.close()

执行输出结果:

blob.png


fetchmany()

import pymysql

# 1.连接
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='123',
    db='dbtest',
    charset='utf8')


# 2.创建游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

sql = 'select * from db2'
cursor.execute(sql)



# 获取2条数据
rows = cursor.fetchmany(2)
print(rows)

# 4.关闭游标

# rows = cursor.fetchall()
# print(rows)
cursor.close()

# 5.关闭连接
conn.close()

执行输出:

blob.png



猜你喜欢

转载自blog.51cto.com/haowen/2129507