前面讲过对文件或简单的持久化存储可以满足一些小应用的需求,而大型服务器或高数据容量的应用则需要更加成熟的数据库系统。但是现在是大数据时间,除了关系型数据外,还会有非关系数据库的支持,才可以在“三高“的系统上,体现性能的优势。本文主要讲述 Python 与关系型数据库(mysql)进行通信。
主要内容
1 需要掌握的技术点
2 安装pymysql
3 pymysql.cursors和 pymysql.connections介绍
4 实现简单的CRUD案例
需要掌握的技术点
1 必须对mysql数据的基本操作要知道,比如说基本的sql 语句的编写,数据库的概念,如果有不了解的同学可 以去 菜鸟教程mysql教程.
2 要有python基础的知语法,毕竟pymysql是通过python来编写程序来处理数据数据的。
安装pymysql
pymysql.connections
在面向对象的世界里万事万物皆对象,connections代表的是应用与数据库之间进行通信需要建立数据库连接。它是最基本的机制,只有通过数据库连接才能把命令传递到服务器,并得到返回的结果。当一个连接(或一个连接池)建立后,可以创建一个游标,向数据库发送请求,然后从数据库中接收回应。
connections 类常见方法详解:
方法名 | 描述 |
---|---|
close() | 关闭数据库连接 |
commit() | 提交当前事务 |
rollback() | 取消当前事务 |
cursor() | 使用该连接创建(并返回)一个游标或类游标的对象 |
errorhandler (cxn, cur, errcls, errval ) | 作为给定连接的游标的处理程序 |
pymysql.cursors
cursors 游标可以让用户提交数据库命令,并获得查询的结果行
cursors 类常见方法详解
方法名或属性 | 描述 |
---|---|
arraysize | 使用 fetchmany()方法时,一次取出的结果行数,默认为 1 |
connection | 创建此游标的连接(可选) |
description | 返回游标活动状态(7 项元组):(name, type_code, display_size, internal_ size, precision, scale, null_ok),只有 name 和 type_code 是必需的 |
lastrowid | 上次修改行的行 ID(可选;如果不支持行 ID,则返回 None) |
rowcount | 上次 execute*()方法处理或影响的行数 |
callproc( func [,args]) | 调用存储过程 |
close() | 关闭游标 |
execute (op[,args]) | 执行数据库查询或命令 |
executemany (op,args) | 类似 execute()和 map()的结合,为给定的所有参数准备并执行数据库查询或命令 |
fetchone() | 获取查询结果的下一行 |
fetchmany([size=cursor. arraysize]) | 获取查询结果的下面 size 行 |
fetchall() | 获取查询结果的所有(剩余)行 |
iter() | 为游标创建迭代器对象(可选,参考 next()) |
messages | 游标执行后从数据库中获得的消息列表(元组集合,可选) |
next () | 被迭代器用于获取查询结果的下一行(可选,类似 fetchone(),参考__iter__()) |
nextset() | 移动到下一个结果集合(如果支持) |
rownumber | 当前结果集中游标的索引(以行为单位,从 0 开始,可选) |
setinputsizes(sizes) | 设置允许的最大输入大小(必须有,但是实现是可选的) |
setoutputsize(size[,col]) | 设置大列获取的最大缓冲区大小(必须有,但是实现是可选的) |
实现简单的CRUD案例
查询数据
import pymysql
#获取连接对象
connection = pymysql.connect("localhost","root","root","users",charset="utf8")
#通过连接对象获取游标
cursor = connection.cursor()
#操作数据
sql = "select * from my_user"
cursor.execute(sql)
#返回影响的行数
#print(cursor.rowcount)
#获取查询数据
#fetchone 获取单条数据 返回是元组类型
# result = cursor.fetchone()
# for message in result:
# print(message)
#获取全部数据
for id,name,address,sex,phone,age,pw in cursor.fetchall():
print(id,name,address,phone,age,pw)
#带参数查询
#操作数据 (查询id= 3 这条记录)
#================1 参数和写死在str中====================
# sql = "select * from my_user where u_id = 3"
#cursor.execute(sql)
#=============2 str动态拼接= (解决不了sql注入问题)====================
# sql = "select * from my_user where u_id = %d " % (4)
# cursor.execute(sql)
#=======3 通过cursor.execute(sql,arge) 参数来实现=====(可以解决sql注入问题)==============
sql = "select * from my_user where u_id = %s "
cursor.execute(sql,[4])
#关闭资源
cursor.close()
connection.close()
sql注入问题
#sql注入问题
import pymysql
#获取连接对象
connection = pymysql.connect("localhost","root","root","users",charset="utf8")
#通过连接对象获取游标
cursor = connection.cursor()
name = "'admin' or 1=1 -- "
pw = "123"
#=============2 str动态拼接= (解决不了sql注入问题)====================
# sql = "select * from my_user where u_name=%s and u_password=%s" % (name,pw)
# cursor.execute(sql)
#=======3 通过cursor.execute(sql,arge) 参数来实现=====(可以解决sql注入问题)==============
sql = "select * from my_user where u_name=%s and u_password=%s"
cursor.execute(sql,[name,pw])
#fetchone 获取单条数据 返回是元组类型
print(cursor.fetchone())
#关闭资源
cursor.close()
插入数据
import pymysql
# 1 Connection 连接 事务 默认是手动提交
message ={"host":"localhost","user":"root","password":"root","database":"test","charset":"utf8"}
connection = pymysql.connect(**message)
# 2 通过connectin对象获取游标
cursor = connection.cursor()
#3 执行语句
#sql ="insert into dept values (null,'研发')"
#添加动态的数据,但是避免不了sql注入
sql ="insert into dept values (null,'%s')" % "行政"
#print(sql)
#添加动态的数据 可以防止sql注入
#sql ="insert into dept values (null,%s)"
#print(sql)
#print(cursor.execute(sql,["人事"]))
print(cursor.execute(sql))
#手动提交事务
connection.commit()
#关闭数据连接
cursor.close()
connection.close()
删除数据
# pymysql 连接数据(删除数据)
import pymysql
#根据地址 ,端口 ,用户 密码,获取连接
message= {"host":"localhost","user":"root","password":"root","database":"test","charset":"utf8"}
#connection = pymysql.connect("localhost","root","root","test")
connection = pymysql.connect(**message)
# 通过连接对象 去获取游标对象 (执行sql)
cursor = connection.cursor()
sql = "delete from myuser where u_id =%s"
#cursor.execute(sql,["李四2","深圳市xx","男",22,12121])
number = cursor.execute(sql,[70])
print(number)
#提交事务
connection.commit()
#关闭资源
cursor.close()
connection.close()
修改数据
# pymysql 连接数据(修改数据)
import pymysql
#根据地址 ,端口 ,用户 密码,获取连接
message= {"host":"localhost","user":"root","password":"root","database":"test","charset":"utf8"}
#connection = pymysql.connect("localhost","root","root","test")
connection = pymysql.connect(**message)
# 通过连接对象 去获取游标对象 (执行sql)
cursor = connection.cursor()
sql = "update myuser set u_name=%s where u_id=%s"
#cursor.execute(sql,["李四2","深圳市xx","男",22,12121])
number = cursor.execute(sql,["张三2",70])
print(number)
#提交事务
connection.commit()
#关闭资源
cursor.close()
connection.close()
如果每次执行操作都需要编写获取连接,执行sql, 关闭资源的代码肯定不合理,那么怎么才可以把代码重用起来,请看后期更新。谢谢!