概述
1、pymysql模块介绍
```python
"""
支持python代码操作数据库MySQL
"""
pip3 install pymysql
```
### sql注入
```python
"""
利用一些语法的特性 书写一些特点的语句实现固定的语法
MySQL利用的是MySQL的注释语法
select * from user where name='jason' -- jhsadklsajdkla' and password=''
select * from user where name='xxx' or 1=1 -- sakjdkljakldjasl' and password=''
"""
日常生活中很多软件在注册的时候都不能含有特殊符号
因为怕你构造出特定的语句入侵数据库 不安全
# 敏感的数据不要自己做拼接 交给execute帮你拼接即可
# 结合数据库完成一个用户的登录功能?
import pymysql
conn = pymysql.connect(
host = '127.0.0.1',
port = 3306,
user = 'root',
password = '123456',
database = 'day48',
charset = 'utf8' # 编码千万不要加-
) # 链接数据库
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
username = input('>>>:')
password = input('>>>:')
sql = "select * from user where name=%s and password=%s"
# 不要手动拼接数据 先用%s占位 之后将需要拼接的数据直接交给execute方法即可
print(sql)
rows = cursor.execute(sql,(username,password)) # 自动识别sql里面的%s用后面元组里面的数据替换
if rows:
print('登录成功')
print(cursor.fetchall())
else:
print('用户名密码错误')
```
* 数据库练习题
```python
"""
1 面对复杂的查询题目的时候 不要捉急 sql语句不要想着一口气写完 分步书写
2 只要是涉及到多表查询的时候 肯定用到联表操作和子查询
联表操作 你可以无限制的联N多张表
将两张表的结果起别名 变成了一张表
之后再去另外一张表拼接再起别名
再去拼接...
3 一定要把昨天上课将的练习题自己能够理解并敲出来
"""
```
* pymysql模块
```python
# 直接安装 无需考虑版本
pip3 install pymysql
import pymysql
conn = pymysql.connect(
host = '127.0.0.1',
port = 3306
user = 'root',
password = '123456', # 还可以简写passwd = '123456'
database = 'db666', # 还可以简写db = 'db666'
charset = 'utf8' # 千万不要加横杆
)
# cursor = conn.cursor() # 括号内不加参数的话 那么查询出来的数据是元组的形式 数据不够明确 容易混乱
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 字典形式返回数据 数据有具体的描述信息 更加的合理方便
sql = 'select * from user'
affect_rows = cursor.execute(sql) # 返回值是当前sql语句执行的受影响的行数
cursor.fetchone() # 只能结果的一条 数据本身
cursor.fetchall() # 拿所有 列表套多个数据
cursor.fetchmany(n) # 指定获取几条
"""
上述三个方法在读取数据的时候有一个类似于文件指针的特点
"""
cursor.scroll(1,'relative') # 相对于光标所在的当前位置往后移动
cursor.scroll(1,'absolute') # 相对于数据开头往后移动
```
* sql注入
```python
"""
就是利用一些特殊字符 结合软件固定的一些语句句式
非法侵入并违规操作
利用MySQL注释的语法 造成了sql注入的问题
用户不需要属于用户名和密码也能够登录并且获取到整个用户表的数据
日常应用软件在获取用户输入的内容时 都会限制一些特殊符号的输入
如何解决上述问题?
所有敏感的信息不要自己去做拼接操作 交互固定的模块帮你去过滤数据防止sql注入
在pymysql中 execute就能够帮你过滤
"""
# sql注入
sql = "select * from user where username='%s' and password='%s'"%(username,password)
# 不要自己拼接
sql = "select * from user where username=%s and password=%s"
execute(sql,(username,password)) # 只能识别%s
```
### pymysql补充
```python
# 1.针对增删改 pymysql需要二次确认才能真正的操作数据
import pymysql
conn = pymysql.connect(
host = '127.0.0.1',
port = 3306,
user = 'root',
passwd = '123456',
db = 'day48',
charset = 'utf8',
autocommit = True
)
cursor = conn.cursor(pymysql.cursors.DictCursor)
# 增
sql = 'insert into user(name,password) values(%s,%s)'
# rows = cursor.execute(sql,('jackson',123))
rows = cursor.executemany(sql,[('xxx',123),('ooo',123),('yyy',123)])
print(rows)
# conn.commit() # 确认
# 修改
# sql = 'update user set name="jasonNB" where id=1'
# rows = cursor.execute(sql)
# print(rows)
# conn.commit() # 确认
# 删除
sql = 'delete from user where id=7'
rows = cursor.execute(sql)
print(rows)
conn.commit() # 确认
# 查
# sql = 'select * from user'
# cursor.execute(sql)
# print(cursor.fetchall())
"""
增删改查中
删改增它们的操作设计到数据的修改
需要二次确认
"""
# 还可以一次性插入N多条数据
rows = cursor.executemany(sql,[('xxx',123),('ooo',123)])
```
pymysql补充
import pymysql
conn = pymysql.connect(
host = '127.0.0.1',
port = 3306,
user = 'root',
passwd = '123456',
db = 'day48',
charset = 'utf8',
autocommit = True
)
cursor = conn.cursor(pymysql.cursors.DictCursor)
# 增
sql = 'insert into user(name,password) values(%s,%s)'
# rows = cursor.execute(sql,('jackson',123))
rows = cursor.executemany(sql,[('xxx',123),('ooo',123),('yyy',123)])
print(rows)
# conn.commit() # 确认
# 修改
# sql = 'update user set name="jasonNB" where id=1'
# rows = cursor.execute(sql)
# print(rows)
# conn.commit() # 确认
# 删除
sql = 'delete from user where id=7'
rows = cursor.execute(sql)
print(rows)
conn.commit() # 确认
# 查
# sql = 'select * from user'
# cursor.execute(sql)
# print(cursor.fetchall())
"""
增删改查中
删改增它们的操作设计到数据的修改
需要二次确认
"""
2、案例1
# -*-coding:utf-8-*-
import pymysql
# 打开数据库连接
conn = pymysql.connect(host='sh-cdb-o2lunkmk.sql.tencentcdb.com',port=60392,user='root',passwd='5stexN@5Z#yra^55',db='bydevice_2021_04_06')
# 使用cursor()方法创建一个游标对象
cursor = conn.cursor()
# 使用execute()方法执行SQL查询
cursor.execute('SELECT VERSION()')
# 使用fetchone()方法获取单条数据
data = cursor.fetchone()
# 打印
print('database version: %s' % data)
# 关闭数据库连接
conn.close()
3、案例2
import pymysql
# 打开数据库连接
conn = pymysql.connect(host='sh-cdb-o2lunkmk.sql.tencentcdb.com',port=60392,user='root',passwd='5stexN@5Z#yra^55',db='bydevice_2021_04_06')
# 使用cursor()方法创建一个游标对象
cursor = conn.cursor()
# 使用cursor()方法创建一个游标对象cursor
cursor = conn.cursor() # 游标对象用于执行查询和获取结果
# 使用execute()方法执行SQL,如果表存在则将其删除
cursor.execute('DROP TABLE IF EXISTS EMPLOYEE112')
# 使用预处理语句创建表
sql = """CREATE TABLE `employee112` (
`first_name` varchar(255) DEFAULT NULL COMMENT '姓',
`last_name` varchar(255) DEFAULT NULL COMMENT '名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`sex` varchar(255) DEFAULT NULL COMMENT '性别',
`income` varchar(255) DEFAULT NULL COMMENT '收入'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
"""
# 执行SQL语句
cursor.execute(sql)
# 关闭数据库连接
conn.close()
4、案例3
import pymysql
def get_conn():
conn = pymysql.connect(host='sh-cdb-o2lunkmk.sql.tencentcdb.com', port=60392, user='root',
passwd='5stexN@5Z#yra^55', db='bydevice_2021_04_06')
return conn
def insert(sql):
conn = get_conn()
cur = conn.cursor()
result = cur.execute(sql)
print(result)
conn.commit()
cur.close()
conn.close()
if __name__ == '__main__':
sql = 'INSERT INTO employee112 VALUES('yao','ming',12,'男',5000)';
insert(sql)
5、案例4
import pymysql
def get_conn():
conn = pymysql.connect(host='sh-cdb-o2lunkmk.sql.tencentcdb.com', port=60392, user='root',
passwd='5stexN@5Z#yra^55', db='bydevice_2021_04_06')
return conn
#
# def insert(sql):
# conn = get_conn()
# cur = conn.cursor()
# result = cur.execute(sql)
# print(result)
# conn.commit()
# cur.close()
# conn.close()
def insert(sql, args):
conn = get_conn()
cur = conn.cursor()
result = cur.execute(sql, args)
print(result)
conn.commit()
cur.close()
conn.close()
if __name__ == '__main__':
sql2 = 'INSERT INTO employee112 VALUES(%s,%s,%s,%s,%s);'
insert(sql2, ('邓', '小平', 120,'男',1000))
6、案例5
import pymysql
def get_conn():
conn = pymysql.connect(host='sh-cdb-o2lunkmk.sql.tencentcdb.com', port=60392, user='root',
passwd='5stexN@5Z#yra^55', db='bydevice_2021_04_06')
return conn
#
# def insert(sql):
# conn = get_conn()
# cur = conn.cursor()
# result = cur.execute(sql)
# print(result)
# conn.commit()
# cur.close()
# conn.close()
#
# def insert(sql, args):
# conn = get_conn()
# cur = conn.cursor()
# result = cur.execute(sql, args)
# print(result)
# conn.commit()
# cur.close()
# conn.close()
def insert_many(sql, args):
conn = get_conn()
cur = conn.cursor()
result = cur.executemany(query=sql, args=args)
print(result)
conn.commit()
cur.close()
conn.close()
if __name__ == '__main__':
sql3 = 'insert into employee112 VALUES (%s,%s,%s,%s,%s)'
args = [('周', '恩来', 130, '男', 1000), ('毛', '泽东', 130, '男', 1002), ('邓', '亚萍', 60, '女', 2002)]
insert_many(sql=sql3,args=args)
7、案例6
import pymysql
def get_conn():
conn = pymysql.connect(host='sh-cdb-o2lunkmk.sql.tencentcdb.com', port=60392, user='root',
passwd='5stexN@5Z#yra^55', db='bydevice_2021_04_06')
return conn
#
# def insert(sql):
# conn = get_conn()
# cur = conn.cursor()
# result = cur.execute(sql)
# print(result)
# conn.commit()
# cur.close()
# conn.close()
#
# def insert(sql, args):
# conn = get_conn()
# cur = conn.cursor()
# result = cur.execute(sql, args)
# print(result)
# conn.commit()
# cur.close()
# conn.close()
def update(sql,args):
conn = get_conn()
cur = conn.cursor()
result = cur.execute(sql,args)
print(result)
conn.commit()
cur.close()
conn.close()
if __name__ == '__main__':
sql = 'UPDATE employee112 SET income=%s WHERE last_name = %s;'
args = (5000, '亚萍')
update(sql, args)
8、案例7
import pymysql
def get_conn():
conn = pymysql.connect(host='sh-cdb-o2lunkmk.sql.tencentcdb.com', port=60392, user='root',
passwd='5stexN@5Z#yra^55', db='bydevice_2021_04_06')
return conn
#
# def insert(sql):
# conn = get_conn()
# cur = conn.cursor()
# result = cur.execute(sql)
# print(result)
# conn.commit()
# cur.close()
# conn.close()
#
# def insert(sql, args):
# conn = get_conn()
# cur = conn.cursor()
# result = cur.execute(sql, args)
# print(result)
# conn.commit()
# cur.close()
# conn.close()
# def update(sql,args):
# conn = get_conn()
# cur = conn.cursor()
# result = cur.execute(sql,args)
# print(result)
# conn.commit()
# cur.close()
# conn.close()
def delete(sql,args):
conn = get_conn()
cur = conn.cursor()
result = cur.execute(sql,args)
print(result)
conn.commit()
cur.close()
conn.close()
if __name__ == '__main__':
sql = 'DELETE FROM employee112 WHERE last_name = %s;'
args = ('恩来',) # 单个元素的tuple写法
delete(sql,args)
9、案例8:
import pymysql
def get_conn():
conn = pymysql.connect(host='sh-cdb-o2lunkmk.sql.tencentcdb.com', port=60392, user='root',
passwd='5stexN@5Z#yra^55', db='bydevice_2021_04_06')
return conn
def query(sql,args):
conn = get_conn()
cur = conn.cursor()
cur.execute(sql,args)
results = cur.fetchall()
print(type(results)) # 返回<class 'tuple'> tuple元组类型
for row in results:
print(row)
firstName = row[0]
lastName = row[1]
age1 = row[2]
sex1 = row[3]
income = row[4]
print('姓:' +firstName + ',名:' +lastName + ',年纪:' + str(age1)+',性别:'+sex1+',收入:'+str(income))
pass
conn.commit()
cur.close()
conn.close()
if __name__ == '__main__':
sql = 'SELECT * FROM employee112;'
query(sql,None)
最后
以上就是感动西装为你收集整理的python操作数据库_pymysql模块1、pymysql模块介绍2、案例13、案例24、案例35、案例4 6、案例57、案例68、案例79、案例8:的全部内容,希望文章能够帮你解决python操作数据库_pymysql模块1、pymysql模块介绍2、案例13、案例24、案例35、案例4 6、案例57、案例68、案例79、案例8:所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复