前置模块
mysqlclient 开源作者methane提供,c构建
PyMySQL 开源作者methane和adamchainz提供,纯python构建
安装方式
1、pip install mysqlclient(依赖virtual环境)
2、下载.whl驱动,使用pip install ***.whl
3、下载tar.gz文件,进入目录,python setip.py install
网站:www.pypi.org
注意:安装前一定要先升级pip ,python -m pip install -- upgrade pip
pip list 查看安装的第三方包
数据库操作API
1.连接数据库
import MySQLdb
conn=MySQLdb.connect(
host='localhost', #连接的主机名
port=3306, #端口号
user='root', #mysql用户名
password='123456, #数据库密码
db='数据库名', #连接的数据库名
charset="utf8") #编码集
2、获取cursor对象
cursor=conn.cursor() #游标对象,对数据库进行操作的对象
3、执行SQL语句
count=cursor.execute("sql语句") 返回受影响sql语句的个数
4、执行查询
cursor.fetchone() 查询一条数据
cursor.fetchmany(index) 查询index条数据
cursor.fetchall() 获取所有数据(元组套元组)
5、删除数据
cursor.execute("删除的sql语句") 但是数据库并未改变
conn.commit() 提交,提交了才删除数据
注意:增删改都需要提交了才生效
conn.rollback() 手动回滚
conn.begin() 开启事务
6、资源回收
作用:
回收资源,减少系统资源的浪费
cursor.close() 回收游标
conn.close() 回收
7、cursor类型选择
以上的cursor执行的查询返回的元组里面的元素都是元组
cursor=conn.cursor(MySQLdb.cursors.DictCursor) 返回的是由字典组成的元组
SQL注入问题
所谓SQL注入,就是通过把SQL命令插入到Web表单提交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令,攻击站点,达到入侵目的。
name="' or '1'='1"
sql = "select id,name,age from user where name='%s'" % name # name = '' or '1'='1'
total = cursor.execute(sql3) #此时执行sql,可以防止sql注入
出现如上问题,根源:sql语句有字符串拼接
name="' or '1'='1"
sql = "select id,name,age from user where name=%s"
total = cursor.execute(sql,[name]) #此时执行sql,其中的参数内容会转义为没有sql语义的片段,可以防止sql注入
2、传递参数
用 %s
或 %(key)s
做占位符,接收参数
sql = "select id,name,age from test where name=%s and id=%s" #%s 做占位符
total = cursor.execute(sql ,["Mr_lee" ,1] ) #列表
sql = "insert into test(name,age) values(%s,%s)" #%s 做占位符
total = cursor.execute(sql ,("Mr_lee" ,18) ) #元组
# %(key)s 做占位符
sql = "select id,name,age from test where name=%(name)s and id>%(id)s"
total = cursor.execute(sql , {"id":1,"name":"Mr_lee"} ) #dict
可以使用cursor.execute(sql,[name])防止