数据库5 不想改

1. mysql 用户数据管理
数据安全非常安全 不可能随便分配 root 账户
应该按照不同开发岗位分配不同的账户和权限

mysql 中 将用户相关数据放在mysql库
user->db -tables_priv ->colimns_priv
如果用户拥有对所有库的使用权 则存储在user中
如果用户拥有对部分库的使用权 则存储在db中
如果用户拥有对部分表的使用权 则存储在tables_priv中
如果用户拥有对部分库的使用权 则存储在colimns_priv中

创建新账户
create user "帐户名"@"主机名" identified by 密码
create user"tom"@"localhost" identified by "123";

授权所有数据库所有表的所有权限给jerry这个用户 并允许jerry在任意电脑上登陆
如果用户不存在会自动创建
grant all on *.* to "jerry"@"%" identified by "123" with grant option;
with grant option 表示该用户可以将自己权限授权给其他人

授予day45数据库的所有表(emp表)的所有权限给jerry 并允许jerry在任意电脑上登陆
grant all on day45.(emp.)* to "jerry"@"%" identified by "123";

授予day45数据库中emp表下name字段的查询给jerry 并允许jerry在任意电脑上登陆
grant select(name) on day45.emp to "jerry"@"%" identified by "123";


收回权限
REVOKE all privileges [column] on db.table from user@"host";

REVOKE all privileges on day45.(emp.)* to "jerry"@"%";

删除用户
drop user@"host" #删除用户
例子:drop user maria@%

立即刷新权限列表
flush privileges;

当你在云服务器部署了mysql环境时 你的程序无法直接连接到服务器 许哟啊授权任意一台主机
grant all on *.* to "jerry"@"%" identified by "123" with grant option;




2. pymysql
后期开发中都是用框架代替mysql


import pymysql
conn=pymysql.connect(
host="127.0.0.1",
port=3306,
user="root",
password="root"
database="day47",#指定数据库
charset="utf-8"
)

# cursor 游标对象负责执行sql语句 获取返回的数据
# pymysql.cursors.DictCursor 指定使用字典类型的游标,默认是元组类型的
cursor = conn.cursor(pymysql.cursors.DictCursor)

sql查询:
sql="select *from user"
res=cursor.execute(sql) #执行sql语句,返回值是本次查询的记录条数
print(cursor.fetchall()) #提取所有结果
cursor.scroll(1,mode="absolute")# 可以指定游标移动位数
print(cursor.fetchone())# 提取单个结果
print(cursor.fetchmany(2))# 提取指定条数结果

sql增删改:
增值:
sql="insert into user values(null,"xxx值1","xxx值n")"
改值:
sql="update xxxx#表名 set name ='xx#新值' where name = 'xxx#值'"
删除:
sql="delete from xxxx#表名 where xx#段名 = 'xxxxx#值'"

res=cursor.execute(sql)
# pymysql 不会自动提交 对数据的修改不会持续化 需要手动commit
conn.commit()
conn.rollback()






3. sql注入:
# 什么是sql注入攻击?
一些了解SQL语法的攻击者 可以通过一些特殊符号来修改sql执行
逻辑 这就是sql注入攻击

#避免的方式:
1. 在输入时加上正则判断 不允许输入与sql相关的关键字 这种方式无法避免代理攻击

2. 在服务器端口 执行sql前先来一波判断
pymysql中已经帮你做了处理 只要将参数的拼接交给pymysql来完成就能够避免攻击

3. sql注入攻击:
name=input("输入用户名:")
pwd=input("输入密码:")
# sql="select *from user where name ='%s' and 'pwd' = %s"%(name,pwd)

举例:
#在上诉程序下:输入名:xxxx' or 1=1 -- xxxxxxx
输入密码:xxxx
#时候会被sql注入攻击成功,显示登陆成功

sql="select *from user where name = %s and 'pwd' = %s"
print(sql)
res=cursor.execute(sql,(name,pwd))
if res:
print("登陆成功")
else:
print("登陆失败")






4. 什么阶段使用可视化
项目开始前 就应该先设计数据库 如果表很多 就需要使用可视化
最好的功能ER吐 可以直接看出表与表之间的关系

原文地址:https://www.cnblogs.com/yanhui1995/p/10007131.html