mysql 07.24

1.用户管理

主要为了控制权限,让不同的开发者,仅能操作属于自己的业务范围内的数据。

创建mysql账户

账户中涉及的三个数据 :账户名 密码 ip地址

create user 用户名@主机地址 identified by '密码';
# 注意:操作用户 只能由root账户来进行
# 删除 将同时删除所有权限
drop user 用户名@主机地址;

权限管理

user 与用户相关信息
db 用户的数据库权限信息
tables_priv 用户的表权限
columns_priv 用户的字段权限
grant all on *.* to 用户名@主机地址 identified by '密码';

#如果用户不存在则自动创建新用户,推荐使用
grant all on *.* to rose@localhost identified by '121';

grant all on day42.* to rose1@localhost identified by '123';

grant all on day42.table1 to rose2@localhost identified by '123';

grant select(name),update(name) on day42.table1 to rose3@localhost identified by '123';

all 表示的是对所有字段的增删改查
*to* 所有库所有表

revoke all on *.*from 用户名@主机地址;

revoke all on day42.table1 from rose2@localhost;

#刷新权限
flush privileges;

#with grant option 表示 可以将他所拥有的权限授予其它的用户
grant all *.* to root1@localhost identified by '123' with grant option;

#授予某个用户 可以在任何主机上登录
grant all on *.* to jack10@'%' identified by '123';
grant all on *.* to jack10@localhost identified by '123';

2.可视化客户端

navicat

3.pymysql

pymysql 是一个第三方模块,帮我们封装了,建立连接,用户认证,sql'的执行以及,结果的获取

基本使用

import pymysql
#1.连接服务器  获取连接对象(本质上就是封装好的socket)
conn = pymysql.connect(
	host = "127.0.0.1",  #如果是本机 可以忽略
    port = 3306,    # 如果没改过 可以忽略
    user = "root", #必填
    password = "111", #必填
    database = "day42" #必填
)
#2.通过连接拿到游标对象
# 默认的游标返回的是元组类型 不方便使用,需要更换字典类型的游标
c = conn.cursor(pymysql.cursors.DictCursor)
#3.执行语句sql
sql = 'select * from table1'
res = c.execute(sql) # 查询语句将返回查询的结果数量

#4.提取结果
print(res)
print(c.fetchall())

#5.关闭连接
c.close()
conn.close()

# 移动光标 参数1位移动的位置   mode 指定 相对或绝对
#c.scroll(1,mode='absolute')

#print(c.fetcharll())

# print(c.fetchmany(1))
print(c.fetchone())
print(c.fetchone())

sql注入攻击

指的是一些程序员,在输入数据时,按照sql 的语法规范,提交了用于攻击性目的的数据。

如何避免这个问题

在服务器端执行sql语句之前做sql的验证

验证操作pymysql已经封装了,我们只需要将参数交给pymysql来做拼接即可

修改数据

import pymysql
conn = pymysql.connect(
    host = "127.0.0.1",  #如果是本机 可以忽略
    port = 3306,    # 如果没改过 可以忽略
    user = "root", #必填
    password = "111", #必填
    database = "day42", #必填,
    #autocommit=False  # 开启自动提交  不常用....
)

c = conn.cursor(pymysql.cursors.DictCursor)
name = input('name:')
pwd = input('pwd:')

sql = 'select *from user where name = %s'

if c.execute(sql,(name,)):
	print('用户已经存在')
else:
	sql2 = 'insert into user values(%s,%s)'
	if c.execute(sql2,(name,pwd)):
		print('注册成功!')
		conn.commit() #调用连接对象的提交函数
	else:
		print('注册失败!')
		
c.close()
conn.close()
#调用存储过程
delimiter |
create procedure add1(in a int,in b int,out c int)
begin
set c = a+b;
end |
delimiter;

#pymysql中调用
import pymysql
conn = pymysql.connect(
    host = "127.0.0.1",  #如果是本机 可以忽略
    port = 3306,    # 如果没改过 可以忽略
    user = "root", #必填
    password = "111", #必填
    database = "day42", #必填,
    autocommit=True  # 开启自动提交  不常用....
)

c = conn.cursor(pymysql.cursors.DictCursor)
c.callpore('add1',(1,2,1212))
c.execute('select @_add1_2')
print(c,fetchone())
posted @ 2019-07-24 23:26  海森t  阅读(33)  评论(0)    收藏  举报