码迷,mamicode.com
首页 > 数据库 > 详细

23-mysql基础

时间:2017-07-21 19:51:29      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:控制台   数据库名   off   字段   img   nod   class   keyword   主机   

目录:mysql,memcached,reids
 
数据库
Datebase,就是一个存放数据的仓库,按照一定的数据结构(数据的组织形式或数据的联系)来组织存储的,我们可以通过数据库提供的多种方法来管理数据库里面的数据。
 
mysql数据库
 
基本操作:
1,查询数据库
> show databases;
技术分享
mysql:用户权限相关的数据
test:用于测试的数据库
information_schema:mysql自身架构相关数据
python_test:自定义创建的数据库
 
2,创建自定义数据库
# 创建一个数据库,名为python_test,默认字符集为utf8
> create database python_test default charset utf8 collate utf8_general_ci;
 
3,要查看一个数据库内的信息,需要先选择该数据库
> use python_test;
 
4,查看所有表的信息
> show tables;
 
5,用户管理
# 创建用户
> create user ‘xiaofei‘@‘192.168.100.0/24‘ identified by ‘123456‘;
 
# 删除用户
> drop user ‘xiaofei‘@‘192.168.100.0/24‘;
 
# 修改用户名
> rename user ‘xiaofei‘@‘192.168.100.0/24‘ to ‘dafei‘@‘192.168.100.0/24‘;
 
# 修改密码
> set password for ‘xiaofei‘@‘192.168.100.0/24‘ = password(‘123.com‘)
 
6,授权管理
默认mysql仅允许本地访问,若要远程连接,需要授权某用户允许访问某数据库或某张表
# 查看用户权限
> show grants for ‘xiaofei‘@‘192.168.100.0/24‘;
# 授权用户对某数据库或某张表有某种权限,all表示所有权限,*表示所有数据库或表
> grant all on python_test to ‘dafei‘@‘192.168.100.0/24‘;
 
# 取消授权
> revoke all on python_test from ‘dafei‘@‘192.168.100.0/24‘;
 
# 让授权立即生效
> flush privileges;
 
7,忘记mysql用户名密码
# 启动免授权服务端
> mysqld --skip-grant-tables
> mysql -uroot -p
> update mysql.user set authentication_string=password(‘666‘) where user=‘root‘;
> flush privileges;
 
补充扩展:
<wiz_code_mirror>
 
 
 
 
 
1
# 权限授权的参数
2
all privileges  除grant外的所有权限
3
            select          仅查权限
4
            select,insert   查和插入权限
5
            ...
6
            usage                   无访问权限
7
            alter                   使用alter table
8
            alter routine           使用alter procedure和drop procedure
9
            create                  使用create table
10
            create routine          使用create procedure
11
            create temporary tables 使用create temporary tables
12
            create user             使用create user、drop user、rename user和revoke  all privileges
13
            create view             使用create view
14
            delete                  使用delete
15
            drop                    使用drop table
16
            execute                 使用call和存储过程
17
            file                    使用select into outfile load data infile
18
            grant option            使用grant revoke
19
            index                   使用index
20
            insert                  使用insert
21
            lock tables             使用lock table
22
            process                 使用show full processlist
23
            select                  使用select
24
            show databases          使用show databases
25
            show view               使用show view
26
            update                  使用update
27
            reload                  使用flush
28
            shutdown                使用mysqladmin shutdown(关闭MySQL)
29
            super                   使用change master、kill、logs、purge、master和set global。还允许mysqladmin????????调试登陆
30
            replication client      服务器位置的访问
31
            replication slave       由复制从属使用
32
?
33
# 对于数据库的参数
34
对于目标数据库以及内部其他:
35
数据库名.*           数据库中的所有
36
数据库名.表          指定数据库中的某张表
37
数据库名.存储过程     指定数据库中的存储过程
38
*.*                 所有数据库
39
    
40
# 对于用户的参数
41
用户名@IP地址         用户只能在改IP下才能访问
42
用户名@192.168.1.%   用户只能在改IP段下才能访问(通配符%表示任意)
43
用户名@%             用户可以再任意IP下访问(默认IP地址为%)
44
> grant all privileges on db1.tb1 TO ‘用户名‘@‘IP‘
45
> grant select on db1.* TO ‘用户名‘@‘IP‘
46
> grant select,insert on *.* TO ‘用户名‘@‘IP‘
47
> revoke select on db1.tb1 from ‘用户名‘@‘IP‘
 
 
 
表的操作:
1,创建表
> create table table_name(
    列名1 类型 是否允许为空,
    列名2 类型 是否允许为空
)engine=Innodb default charset=utf8;
<wiz_code_mirror>
 
 
 
 
 
1
# 是否允许为空
2
not null
3
null
4
?
5
# 默认值,创建列时,可指定默认值,即若不指定列属性,应用默认属性
6
> create table tb1(
7
    nid int not null default 2,
8
    num int not null
9
);
10
?
11
# 设置自增
12
> create table tb1(
13
    nid int not null auto_increment primary key,
14
    num int null
15
);
16
?
17
> create table tb2(
18
    nid int not null auto_increment,
19
    num int null,
20
    index(nid)
21
)
22
?
23
# 注:对于自增列必须是索引,含主键;对于自增,可以设置起始值和步长
24
# 会话级别的设置,全局级别设置将session改成global即可
25
> show session variables like ‘auto_inc%‘;
26
+--------------------------+-------+
27
| Variable_name            | Value |
28
+--------------------------+-------+
29
| auto_increment_increment | 1     |
30
| auto_increment_offset    | 1     |
31
+--------------------------+-------+
32
> set  session auto_increment_increment=2;
33
> set session auto_increment_offset=10;
34
?
35
# 主键设置,主键是一种特殊的且唯一的索引,不允许为空,如果主键使用单个列,则它的值必须唯一,如果是多列,则其组合必须唯一.
36
> create table tb1(
37
    nid int not null auto_increment primary key,
38
    num int null
39
)
40
?
41
> create table tb2(
42
    nid int not null,
43
    num int not null,
44
    primary key(nid,num)
45
)
46
?
47
# 外键设置,外键是一种特殊的索引,只能是指定内容
48
> create table color(
49
    nid int not null primary key,
50
    name char(16) not null
51
)    
52
?
53
> create table fruit(
54
    nid int not null primary key,
55
    smt char(32) null,
56
    color_id int not null,
57
    constraint fk_cc foreign key (color_id) references color(nid)
58
)
 
 
 
2,删除表
> drop table 表名;
 
3,清空表
> delete from 表名;
> truncate table 表名;
区别:
delete删除后,再次插入,自增id会从删除前的id继续增加
truncate清空后,自增id会从初始值增加
 
4,修改表
# 添加列:
> alter table 表名 add 列名 类型;
 
# 删除列:
> alter table 表名 drop column 列名;
 
# 修改列:
> alter table 表名 modify column 列名 类型;
> alter table 表名 change 原列名 类型;
 
# 添加主键:
> alter table 表名 add primary key(列名);
 
# 删除主键:
> alter table 表名 drop primary key;
> alter table 表名 modify 列名 int, drop primary key;
 
# 添加外键:
> alter table 从表 add constraint 外键名称(形如:FK_从表_主表) foreign key 从表(外键字段) references 主表(主键字段);
 
# 删除外键:
> alter table 表名 drop foreign key 外键名称
 
# 修改默认值:
> ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;
 
# 删除默认值:
> ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;
表数据操作
增insert
> insert into 表 (列名1,列名2,...) values (值1,值2,...);
> insert into 表 (列名1,列名2,...) values (值1,值1,...), (值2,值2,...);
> insert into 表 (列名1,列名2,...) select (列名3,列名4,...) from 表;
 
删delete
> delete from 表;
> delete from 表 where id=1 and name=‘alex‘;
 
改update
> update 表 set name=‘alex‘ where id > 1;
 
查select
> select * from 表;
> select * from 表 where id > 1;
> select nid,name,gender as gg from 表 where id > 1;
 
其他操作
a、条件
select * from 表 where id > 1 and name != ‘alex‘ and num = 12;
 
select * from 表 where id between 5 and 16;
 
select * from 表 where id in (11,22,33)
select * from 表 where id not in (11,22,33)
select * from 表 where id in (select nid from 表)
 
b、通配符
select * from 表 where name like ‘ale%‘ - ale开头的所有(多个字符串)
select * from 表 where name like ‘ale_‘ - ale开头的所有(一个字符)
 
c、限制
select * from 表 limit 5; - 前5行
select * from 表 limit 4,5; - 从第4行开始的5行
select * from 表 limit 5 offset 4 - 从第4行开始的5行
 
d、排序
select * from 表 order by 列 asc - 根据 “列” 从小到大排列
select * from 表 order by 列 desc - 根据 “列” 从大到小排列
select * from 表 order by 列1 desc,列2 asc - 根据 “列1” 从大到小排列,如果相同则按列2从小到大排序
 
e、分组
select num from 表 group by num
select num,nid from 表 group by num,nid
select num,nid from 表 where nid > 10 group by num,nid order nid desc
select num,nid,count(*),sum(score),max(score),min(score) from 表 group by num,nid
 
select num from 表 group by num having max(id) > 10
 
特别的:group by 必须在where之后,order by之前
 
f、连表
无对应关系则不显示
select A.num, A.name, B.name
from A,B
Where A.nid = B.nid
 
无对应关系则不显示
select A.num, A.name, B.name
from A inner join B
on A.nid = B.nid
 
A表所有显示,如果B中无对应关系,则值为null
select A.num, A.name, B.name
from A left join B
on A.nid = B.nid
 
B表所有显示,如果B中无对应关系,则值为null
select A.num, A.name, B.name
from A right join B
on A.nid = B.nid
 
g、组合
组合,自动处理重合
select nickname
from A
union
select name
from B
 
组合,不处理重合
select nickname
from A
union all
select name
from B
事务
MySQL 事务主要用于处理操作量大,复杂度高的数据。比如说,在人员管理系统中,你删除一个人员,你即需要删除人员的基本资料,也要删除和该人员相关的信息,如信箱,文章等等,这样,这些数据库操作语句就构成一个事务!
 
1,在MySQL中只有使用了Innodb数据库引擎的数据库或表才支持事务
2,事务处理可以用来维护数据库的完整性,保证成批的SQL语句要么全部执行,要么全部不执行
3,事务用来管理insert,update,delete语句
 
一般来说,事务是必须满足4个条件(ACID): Atomicity(原子性)、Consistency(稳定性)、Isolation(隔离性)、Durability(可靠性)
1,事务的原子性:一组事务,要么成功;要么撤回。
2,稳定性 : 有非法数据(外键约束之类),事务撤回。
3,隔离性:事务独立运行。一个事务处理后的结果,影响了其他事务,那么其他事务会撤回。事务的100%隔离,需要牺牲速度。
4,可靠性:软、硬件崩溃后,InnoDB数据表驱动会利用日志文件重构修改。可靠性和高速度不可兼得, innodb_flush_log_at_trx_commit选项 决定什么时候吧事务保存到日志里。
 
Mysql控制台操作事务:
mysql> begin; #开始一个事务
mysql> insert into a (a) values(555);
mysql>rollback; 回滚 , 这样数据是不会写入的
如果上述操作正常,就可以提交commit关闭事务
 
pymysql使用
1,需要安装,py3不支持mysqlDB, pymysql和mysqldb的用法一样
pip install pymysql
 
2,用法
注意:增删改都需要commit提交事务才会生效
<wiz_code_mirror>
 
 
 
 
 
1
import pymysql
2

3
# 创建连接
4
conn = pymysql.connect(host=‘10.18.210.139‘, port=3306, user=‘root‘, passwd=‘12345‘, db=‘oldboy‘)
5
# 创建游标
6
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  #输出变成字典格式
7
#cursor = conn.cursor()
8

9
# 执行SQL,并返回收影响行数
10
effect_row = cursor.execute("select * from t1",)
11

12
# 不能用先拼接字符串在传入,那样容易sql注入, 比如 root or 1=1 -- 这样传入就会产生sql注入
13
# 执行SQL,并返回受影响行数
14
# effect_row = cursor.execute("update hosts set host = ‘1.1.1.2‘ where nid > %s", (1,))
15

16
# 执行SQL,并返回受影响行数
17
# effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])
18

19
# 提交,不然无法保存新建或者修改的数据、删除数据--提交事务
20
conn.commit()
21

22
#拿出是元组/字典类型结果
23
res = cursor.fetchone() #得到一个结果,在次fetchone会在上次的基础上继续取数据
24
# res = cursor.fetchall()
25
# res = cursor.fetchmany(3)  #一次取3个
26
# 关闭游标
27
cursor.close()
28
# 关闭连接
29
conn.close()
30
print (res)
31

32
#最新的最后一条自增id,拿的是自己的
33
new_id  = cursor.lastrowid
34

35
cursor.scroll(1,mode=‘relative‘) #相对当前位置移动
36
cursor.scroll(1,mode=‘absolute‘) #相对绝对位置移动,第一个参数为1就会从1开始开始移动
 
 
 
示例:
1,用html展示单表,一对多,多对多
<wiz_code_mirror>
 
 
 
 
 
1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
    <meta charset="UTF-8">
5
    <title>Title</title>
6
</head>
7
<body>
8
<h1>单表</h1>
9
    <p>
10
        主机名: <input type="text" />
11
    </p>
12
    <p>
13
        端口: <input type="text" />
14
    </p>
15
    <h1>一对多</h1>
16
    <p>
17
        主机名: <input type="text" />
18
    </p>
19
    <p>
20
        端口: <input type="text" />
21
    </p>
22
    <p>
23
        <select>
24
            <option>刘一</option>
25
            <option>刘二</option>
26
            <option>刘上</option>
27
        </select>
28
    </p>
29
    <h1>多对多</h1>
30
    <p>
31
        主机名: <input type="text" />
32
    </p>
33
    <p>
34
        端口: <input type="text" />
35
    </p>
36
    <p>
37
        <select multiple>
38
            <option>刘一</option>
39
            <option>刘二</option>
40
            <option>刘上</option>
41
        </select>
42
    </p>
43
</body>
44
</html>
 
 
效果图如下:
技术分享
 
2,用户登录重写
<wiz_code_mirror>
 
 
 
 
 
1
#!/usr/bin/python
2
# -*- coding:utf-8 -*-
3
import pymysql
4

5
user = input(‘请输入用户名:‘)
6
pwd = input(‘请输入密码:‘)
7

8
# 获取数据
9
conn = pymysql.Connect(host=‘192.168.12.89‘,port=3306,user=‘root‘,password="123",database="s17day11db",charset=‘utf8‘)
10
cursor = conn.cursor()
11
sql = ‘select * from userinfo where username="%s" and password="%s" ‘ %(user,pwd,)
12
# user = alex" --
13
# pwd= asdf
14
‘select * from userinfo where username="alex" -- " and password="sdfsdf"‘
15
# user = asdfasdf" or 1=1  --
16
# pwd= asdf
17
‘select * from userinfo where username="asdfasdf" or 1=1  -- " and password="asdfasdf"‘
18
v = cursor.execute(sql)
19
result = cursor.fetchone()
20
cursor.close()
21
conn.close()
22

23
print(result)
 
 
3,练习
<wiz_code_mirror>
 
 
 
 
 
1
import pymysql
2

3
user = input(‘请输入用户名:‘)
4
pwd = input(‘请输入密码:‘)
5

6
# 获取数据
7
conn = pymysql.Connect(host=‘192.168.12.89‘,port=3306,user=‘root‘,password="123",database="s17day11db",charset=‘utf8‘)
8
cursor = conn.cursor()
9

10
v = cursor.execute(‘select * from userinfo where username=%s and password=%s‘,[user,pwd])
11
result = cursor.fetchone()
12
cursor.close()
13
conn.close()
14

15
print(result)
 
 
4,新建数据
<wiz_code_mirror>
 
 
 
 
 
1
import pymysql
2

3
# 获取数据
4
conn = pymysql.Connect(host=‘192.168.12.89‘,port=3306,user=‘root‘,password="123",database="s17day11db",charset=‘utf8‘)
5
cursor = conn.cursor()
6

7
cursor.execute(‘insert into class(caption) values(%s)‘,[‘新班级‘])
8
conn.commit()
9
new_class_id = cursor.lastrowid # 获取新增数据自增ID
10

11
cursor.execute(‘insert into student(sname,gender,class_id) values(%s,%s,%s)‘,[‘李杰‘,‘男‘,new_class_id])
12
conn.commit()
13

14
cursor.close()
15
conn.close()
 
 
 
 
 
 
 

23-mysql基础

标签:控制台   数据库名   off   字段   img   nod   class   keyword   主机   

原文地址:http://www.cnblogs.com/xiaofeiweb/p/7219250.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!