- Python连接mysql几种方法:https://segmentfault.com/a/1190000041185416
- PyMySQL 是纯 Python 实现的驱动,速度上比不上 MySQLdb,最大的特点可能就是它的安装方式没那么繁琐,同时也兼容
- 参考:https://www.letianbiji.com/python-pymysql/pymysql-install.html
- 要防止SQL注入
使用pymysql库访问MySQL数据库可分为以下几步:
(1) 创建连接。通过connect()方法创建用于连接数据库的Connection对象。 (2) 获取游标。通过Connection对象的cursor()方法创建Cursor对象。 (3) 执行SQL语句。通过Cursor对象的execute()、fetchone()或fetchall()方法执行SQL语句,实现数据库基本操作,包括数据的增加、更新、删除、查询等。 (4) 关闭游标。通过Cursor对象的close()方法关闭游标。 (5) 关闭连接。通过Connection对象的close()方法关闭连接。
一 基本使用
下载pymysql
pip install mysql
创建连接对象以及游标
import pymysql
if __name__ == '__main__':
# 创建连接对象
db = pymysql.connect(host='localhost',
user='root',
passwd='',
db='ehsy_data', # 数据库名字
port=3306,
autocommit=True, # 指定 autocommit 为 True
charset='utf8')
# 创建游标对象
# pymysql.cursors.DictCursor 以字典的形式返回查询出来的数据
cursor = db.cursor(pymysql.cursors.DictCursor)
查询操作
# 查询多条数据
sql = "select * from st_info"
cursor.execute(sql) # 执行SQL语句
res = cursor.fetchall()
print(res)
# 插入操作
cursor.close() # 关闭游标
db.close() # 关闭数据库连接
结果:
[
{'id': 1, 'name': 'lisi', 'password': '123456'},
{'id': 2, 'name': 'lisi', 'password': '123456'}
]
插入、更新、删除操作
- 增删改操作,需要执行
db.commit()
,否则不会提交给数据库- 增删改操作,指定数据有两种方式:
- 以元组方式指定数据:
sql = "insert into st_info(id,name,password) values (%s,%s,%s)"
cursor.execute(sql,(7,'lisi','123456'))
- 占位符用`%s`,不需要用`'%s'`(即使是字段名是字符串,也不需要用`'%s'`),pymysql会自动处理
- 以字典方式指定数据
sql = "insert into st_info(id,name,password) values (%(id)s,%(name)s,%(password)s)"
cursor.execute(sql,{'id':10,'name':'lisi','password':'123456'})
- `%(name)s`是占位符,其中name要与字典中的键名相同
- 上述指定数据方式,在execute方法中有说明:
If args is a list or tuple, %s can be used as a placeholder in the query.
If args is a dict, %(name)s can be used as a placeholder in the query.
- 以上操作后,需要关闭游标以及数据库连接
cursor.close()
db.close()
插入操作
# 插入操作
sql = "insert into st_info(id,name,password) values (%s,%s,%s)"
# 以元组方式指定插入数据
data = (7,'lisi','123456')
cursor.execute(sql,data)
db.commit()
# 以字典形式指定插入的数据
sql = "insert into st_info(id,name,password) values (%(id)s,%(name)s,%(password)s)"
data = {'id':10,'name':'lisi','password':'123456'}
cursor.execute(sql,data)
db.commit()
更新操作
# 更新操作
sql = " update st_info set name=%s where id=%s"
cursor.execute(sql,('wangwu',12))
db.commit()
删除操作
# 删除操作
sql = " delete from st_info where id=%s "
cursor.execute(sql,12)
db.commit()
二 SQL注入问题
- sql注入 就是利用注释等具有特殊意义的符号来完成一些骚操作
- 后续写sql语句 不要手动拼接关键性的数据,而是让excute帮你去做拼接(使用参数化语句添加数据——使用元组/字典指定数据)
以下代码会产生SQL注入问题
# 手动拼接SQL语句
# 方式一
sql = """ insert into st_info(id,name ,password) values ({},'{}','{}') """.format(5,'lisi','123456')
# 方式二
sql = "select * from user where username='%s' and password='%s'"%(username,password)
pymysql 的参数化语句本质上仍然是组装 sql,不过会对数据进行安全转义,以防止 sql 注入。
sql = "insert into st_info(id,name,password) values (%s,%s,%s)"
三 封装pymysql
许多操作有重复代码,我们尝试进行封装,便于调用
import pymysql
from config import host, user, password, db, charset, port
class DB():
def __init__(self):
self.host = host
self.user = user
self.password = password
self.dbName = db
self.charset = charset
self.port = port
# 连接数据库
def connet(self):
try:
# 连接数据库
self.conn = pymysql.connect(
host=self.host,
user=self.user,
password=self.password,
db=self.dbName,
port=self.port,
charset=self.charset,
)
# 获得游标
# pymysql.cursors.DictCursor 以字典的形式返回查询出来的数据
self.cursor = self.conn.cursor(pymysql.cursors.DictCursor)
except Exception as e:
print(str(e)) # 实际中可以写在日志中
# 关闭游标、数据库
def close(self):
try:
# 关闭游标
self.cursor.close()
# 关闭数据库
self.conn.close()
except Exception as e:
print(str(e))
# 查询多条数据
def get_all(self, sql):
try:
self.connet()
self.cursor.execute(sql)
res = self.cursor.fetchall()
self.close()
except Exception as e:
print(str(e))
return res
# 插入、更新、删除操作公共方法
def edit(self, sql):
try:
self.connet()
self.cursor.execute(sql)
# 插入、更新、删除操作必须进行commit
self.conn.commit()
self.close()
except Exception as e:
print(str(e))
# 数据库插入、更新、删除操作
def insert(self, sql):
return self.edit(sql)
def update(self, sql):
return self.edit(sql)
def delete(self, sql):
return self.edit(sql)
- 其中数据库连接信息写在根目录下面的config.py 中
调用封装类 ```python from pymysqlStudy.connect_mysql_impro import DBhost = 'localhost' user = 'root' password = '' db = 'ehsy_data' charset = 'utf8' port = 3306
if name == ‘main‘: db = DB()
# sql = " insert into st_info(id,name,password) values (%s,%s,%s)"
# data = (11,'lisi','123456')
# db.insert(sql,data)
# 更新操作
sql = " update st_info set name=%s where id=%s"
data = ('lisi',11)
db.update(sql,data)
```