MySQL操作

操作数据库之前,我们应该了解什么是数据库?什么是数据表?什么是数据行、列等。简单来说

  • 数据库就 表示我们创建的文件夹
  • 数据表就 表示我们创建的文件夹里的文件
  • 数据行、列就 表示我们创建的文件里的一行一列数据。

数据库操作

首先以root用户登陆后,查看数据库。

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

这是我们装完mysql后,系统自带的数据库,我们不可删除,也不能随便修改。

  • mysql - 用户权限相关数据
  • information_schema - MySQL本身架构相关数据

下面我们一自己创建的数据库 ta为例

create database ta;# 创建数据库

 use ta; #使用数据库

用户管理

 create user 'aa'@'127.0.0.1' identified by '123456'; #创建用户

'aa'表示用户名
'127.0.0.1' 表示IP地址,也可使用localhost 
'123456' 表示密码

重新打开一个终端连接课连接成功

mysql -u aa -h 127.0.0.1 -p
rename user 'aa'@'127.0.0.1' to 'bb'@localhost;  #修改用户

set password for 'bb'@localhost = Password('123'); #修改用户密码

drop user 'bb'@localhost;   #删除用户

用户授权  

默认创建的用户没有权限,我们查看一下

mysql> show grants for 'bb'@'127.0.0.1';
+----------------------------------------+
| Grants for bb@127.0.0.1                |
+----------------------------------------+
| GRANT USAGE ON *.* TO 'bb'@'127.0.0.1' |
+----------------------------------------+

如果想有什么操作,可对用添加什么

grant select on *.* to 'bb'@'127.0.0.1';  #赋予权限
revoke select on *.* from 'bb'@'127.0.0.1'; #解除权限

#*.*表示root用户下的数据库中下的表

下面是所有的权限

all privileges  除grant外的所有权限
            select          仅查权限
            select,insert   查和插入权限
            ...
            usage                   无访问权限
            alter                   使用alter table
            alter routine           使用alter procedure和drop procedure
            create                  使用create table
            create routine          使用create procedure
            create temporary tables 使用create temporary tables
            create user             使用create user、drop user、rename user和revoke  all privileges
            create view             使用create view
            delete                  使用delete
            drop                    使用drop table
            execute                 使用call和存储过程
            file                    使用select into outfile 和 load data infile
            grant option            使用grant 和 revoke
            index                   使用index
            insert                  使用insert
            lock tables             使用lock table
            process                 使用show full processlist
            select                  使用select
            show databases          使用show databases
            show view               使用show view
            update                  使用update
            reload                  使用flush
            shutdown                使用mysqladmin shutdown(关闭MySQL)
            super                   􏱂􏰈使用change master、kill、logs、purge、master和set global。还允许mysqladmin􏵗􏵘􏲊􏲋调试登陆
            replication client      服务器位置的访问
            replication slave       由复制从属使用

权限
权限

 

数据表操作

在创建的数据库ta下操作,初始为空

use ta;                #进入数据库ta
show tables;      #查看表

数据表中包括最常用的增删改查等操作

创建表

mysql> create table tab(
    -> ind int auto_increment primary key,
    -> num int not null  defalut 2,
    -> name varchar(20)
    -> )engine=innodb default charset=utf8;
#ind,num,name 表示列名
#int,archar 表示该列的类型
#auto_increment 表示自增,但只有是在为主键下才能设置
#primary key 表示主键,主键唯一且不为空
# defalut 2表示默认值

如果有两个表的想要有关联的情况下,可以使用外键进行关联

mysql> alter table user add constraint fk_u_p foreign key user(part_id) referenc
es part(nid);
Query OK, 0 rows affected (1.93 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc user;
+---------+-------------+------+-----+---------+----------------+
| Field   | Type        | Null | Key | Default | Extra          |
+---------+-------------+------+-----+---------+----------------+
| ind     | int(11)     | NO   | PRI | NULL    | auto_increment |
| name    | varchar(20) | NO   |     | NULL    |                |
| part_id | int(11)     | YES  | MUL | NULL    |                |
+---------+-------------+------+-----+---------+----------------+
3 rows in set (0.08 sec)

mysql> desc part;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| nid      | int(11)     | NO   | PRI | NULL    | auto_increment |
| partment | varchar(20) | YES  |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

#注释:fk_u_p 表示关联名,跟自己喜好起名
#desc : 查看表结构
#user 从表 part 主表  

删除外键

alter table part drop foreign key fk_u_p;

清空、删除、修改

drop table user; #删除表

delete from part;     #清空表 
truncate table part; #清空表,
#注意的是,delete清空表时,下次添加数据自增的数据会从删除前的位置开始自增。而truncate直接回滚到初始状态

#修改表part
alter table part add name varchar(20); #新增加一条列
alter table part drop column name; #删除列

alter table part change nid id int;# 修改表的名字和类型
alter table part modify column id int; # 修改表的类型

alter table part drop primary key; #删除主键

alter table part alter id set default 2;#修改默认值
alter table part alter id drop default; #删除默认值

数据表内容操作

创建表tab

添加数据
insert into tab(num,name) values('2','aa'); #一次添加一条
insert into tab(num,name) values('3','bb'),('4','dd'); #一次添加多条
insert into tab(num,name...) select (num,name...) from tab

删除表
delete from tab; #删除表中全部数据
 delete from tab where ind = '4'; #删除表中指定的数据

修改表
update tab set num = 3 where ind = 5;

查看表
mysql> select * from tab where ind > 5;
+-----+-----+------+
| ind | num | name |
+-----+-----+------+
|   6 |   2 | aa   |
+-----+-----+------+
mysql> select ind,name as n from tab where ind>5; #改变name 为n
+-----+------+
| ind | n   |
+-----+------+
|   6 | aa   |
+-----+------+

  

其他类型操作  

通配符
select * from tab where name like 'a%'; #%匹配多个字符串
select * from tab where name like 'a_';  #匹配一个字符串

限制条件
select  * from tab limit 3;  #匹配前3行
select  * from tab limit 2,4;  # 匹配从第2行开始的4行
select * from tab limit 4 offset 2; # 匹配从第2行开始的4行 ,效率比上一个高

排序
select * from tab order by ind asc; #将列ind从小到大排列
select * from tab order by ind desc; #将列ind从大到小排列
select * from tab order by name desc,ind asc; #先以列name 排序,如果有相同,以列ind排列

分组
select ind,num from tab group by ind,num;

mysql> select ind,num from tab where ind > 8 group by ind,num order by ind desc;
+-----+-----+
| ind | num |
+-----+-----+
|  11 |   2 |
|  10 |   2 |
|   9 |   2 |
+-----+-----+

select num,ind,count(*),sum(num),max(ind),min(num) from tab 

select num from 表 group by num having max(id) > 10 #having 聚合

特别的:group by 必须在where之后,order by之前
group by num,ind; #sum求和,max取最大,min去最小

连表
select * from 表a,表b where a.列 = b.列 #无对应关系时则不会显示
select * from 表a inner join 表b on a.列=b.列 #无对应关系则不显示,不会出现null
select * from 表a left join 表b on a.列 = b.列 #以a表为准,找出b表对应的列
select * from 表a right join 表b on a.列 = b.列 #以b表为准,找出a表对应的列

组合
select nickname from tab union select name from tab1;#如果表tab和表tab1有重复,则只显示一次
select nickname from tab union all select name from tab1; #有重复也显示全部

pycharm操作mysql

import pymysql

#创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root',passwd='123456', db='example', charset='utf8')

#创建游标
cursor = conn.cursor()

#操作数据
# inp = input(">>>>")
# cursor.execute('insert into class(caption) values(%s)',inp) #防止SQL注入
# #提交
# conn.commit()

#查找数据
r = cursor.execute('select * from student')
l = cursor.fetchall()
for i in l:
    print(i[0])

#关闭游标
cursor.close()
#关闭连接
conn.close()
View Code

 

  

  

  

 

 

 

  

  

  

  

 

posted @ 2017-02-08 17:34  Dwyane.wang  阅读(245)  评论(0编辑  收藏  举报