Python全栈(三)数据库优化之2.数据库的操作与数据表的操作

一、SQL介绍&常见的数据类型

1.SQL定义

SQL是结构化查询语言,是一种用来操作RDBMS(关系型数据库管理系统)的数据库语言。
当前关系型数据库都支持使用SQL语言进行操作,也就是说可以通过SQL操作oracle,sql server,mysql等关系型数据库。

SQL语句分为:
DQL数据查询语言:
用于对数据进行查询,如select;
DML数据操作语言:
对数据进行增加、修改、删除,如insert、udpate、delete;
DDL数据定义语言:
进行数据库、表的管理等,如create、drop。
重点是数据的CURD(增删改查)。

2.数据的完整性:

在表中为了更加准确的存储数据,保证数据的正确有效,可以在创建表的时候,为表添加一些强制性的验证,包括数据字段的类型、约束。

常见的数据类型:

整型int;
小数decimal:
decimal表示浮点数,如decimal(5,2)表示共存5位数,小数占2位.
字符串varchar、char:
varchar是可变长度的字符串,如varchar(3),填充’ab’时会存储’ab’;
char是固定长度字符串,如char(3),填充’ab’时会存储’ab '(ab后有一个空格);
字符串text用于存储大文本,当字符数大于4000时推荐使用。
※对于图片、音频、文本等二进制文件,不存储在数据库中,而是上传到某个服务器上,然后在表中存储这个文件的保存地址。
日期时间date、time、datetime。
枚举类型enum:
把所有可能列举出来,如性别只有2种男、女,星期只有周一到周日7种。

数值类型:

数值类型

字符串:

字符串

日期时间类型:

日期时间

二、数据库约束&数据库简单操作

1.约束

主键primary key:物理上存储的顺序,取值唯一,可以设置自增,并且只能是主键设置自增,其他字段不能设置自增,且主键不能设置默认值;
非空not null:此字段不允许填写空值;
无符号unsigned:没有负值;
自增auto_increment:主键自动增加;
唯一unique:此字段的值不允许重复;
默认default:当不填写此值时会使用默认值,如果填写时以填写为准;
外键foreign key:对关系字段进行约束,当为关系字段填写值时,会到关联的表中查询此值是否存在,如果存在则填写成功,如果不存在则填写失败并抛出异常。

2.数据库操作

操作都是基于命令行的,SQL语句后需要用分号结尾
数据库的连接:

--连接数据库
mysql -u root -proot --不安全,密码直接显示,不推荐

结果:

mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 94
Server version: 5.7.26 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

或者

mysql -uroot -p
Enter password: ****
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 97
Server version: 5.7.26 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

此时会提示输入密码,密码默认为root。
退出数据库

--退出数据库
exit --或者quit

打印

mysql> exit
Bye

查看所有数据库

--查看所有数据库
show databases;

打印

+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+
5 rows in set (0.01 sec)

显示数据库版本

--显示数据库版本
select version();

打印

+-----------+          
| version() |          
+-----------+          
| 5.7.26    |          
+-----------+          
1 row in set (0.00 sec)
                       
mysql>                 

显示时间

--查询时间
select now();

打印

+---------------------+
| now()               |
+---------------------+
| 2019-11-29 16:47:56 |
+---------------------+
1 row in set (0.00 sec)

创建数据库

--创建数据库
create database pythontest;

打印

Query OK, 1 row affected (0.00 sec)

创建数据库时设置编码方式

--创建数据库(设置编码方式)
create database pythontest charset=utf8;

查看创建数据库的命令

--查看创建数据库的语句
show create database pythontest;

打印

+------------+---------------------------------------------------------------------------------------------+
| Database   | Create Database                                                                             |
+------------+---------------------------------------------------------------------------------------------+
| pythontest | CREATE DATABASE `pythontest` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */ |
+------------+---------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)                                                                                     

使用数据库

--使用数据库
use test;

打印

Database changed

查看当前使用的数据库

--查看当前使用的数据库
select database();

打印

+------------+         
| database() |         
+------------+         
| test       |         
+------------+         
1 row in set (0.00 sec)

删除数据库
这一语句需要慎用,

--删除数据库
drop database test;

打印

Query OK, 1 row affected (0.01 sec)

三、数据表的操作和数据插入

1.数据表的操作

查看当前数据库中所有表

--查看当前数据库中所有的表
show tables;

打印

+----------------+     
| Tables_in_demo |     
+----------------+     
| test           |     
+----------------+     
1 row in set (0.00 sec)

创建表

--create table tablename(字段 约束[,字段 约束 类型]);
create table demo1(
    id int,
    name varchar(30)
);

打印

Query OK, 0 rows affected (0.01 sec)

查看表结构

--desc 数据表的名字;
desc demo1;

打印

+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | YES  |     | NULL    |       |
| name  | varchar(30) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
--创建students表(id、name、age、high、gender、cls_id)
create table students(
    id int not null primary key auto_increment,
    name varchar(30),
    age tinyint unsigned default 18,
    height decimal(5,2),
    gender enum('male','female','secret') default 'secret',     --存数据时,只能存male、female、secret三个值,不能存其他的值。
    cls_id int
);

打印

Query OK, 0 rows affected (0.00 sec)

查看表的创建语句

-- show create table 表名字;
show create table students;

打印

+----------+-------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------+                                          
| Table    | Create Table                                                                                          
                                                                                                                   
                                                                                                                   
                                                                        |                                          
+----------+-------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------+                                          
| students | CREATE TABLE `students` (                                                                             
  `id` int(11) NOT NULL AUTO_INCREMENT,                                                                            
  `NAME` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,                                                         
  `age` tinyint(3) unsigned DEFAULT '18',                                                                          
  `height` decimal(5,2) DEFAULT NULL,                                                                              
  `gender` enum('male','female','secret') COLLATE utf8_unicode_ci DEFAULT 'secret',                                
  `cls_id` int(11) DEFAULT NULL,                                                                                   
  PRIMARY KEY (`id`)                                                                                               
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |                                                     
+----------+-------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------+                                          
1 row in set (0.00 sec)                                                                                            

创建classes表(id、name):

create table classes(
    id int primary key not null auto_increment,
    name varchar(30)
);

打印

Query OK, 0 rows affected (0.01 sec)

修改表-添加字段

-- alter table 表名 add 列名 类型;
alter table students add birthday date;

打印

Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

修改表-修改字段(不重命名)

-- alter table 表名 modify 列名 类型及约束;
alter table students modify birthday date default '1990-1-1';

打印

Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

修改表-修改字段(重命名)

-- alter table 表名 change 原名 新名 类型及约束
alter table students change birthday birth date default '1990-1-1';

打印

Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

修改表-删除字段

-- alter table 表名 drop 列名;
alter table students drop height;

打印

Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

删除表或者数据库

drop table 表名;
drop database 数据库;

2.数据插入

全列插入

--insert [into] 表名 values(...);
--向classes中插入一个班级
insert into classes values(1,'class1');
select * from classes;

打印

Query OK, 1 row affected (0.00 sec)

+----+--------+
| id | name   |
+----+--------+
|  1 | class1 |
+----+--------+
1 row in set (0.00 sec)

主键字段是自增的,用0、null、default来占位。

--向students表插入一个学生信息
insert into students values(0,'Tom',18,1,1,'1999-9-9');
insert into students values(null,'Jerry',19,1,1,'1999-10-9');
insert into students values(default,'Nancy',17,1,2,'1999-8-9');
select * from students;

打印

Query OK, 1 row affected (0.00 sec)                     
                                                        
Query OK, 1 row affected (0.00 sec)                     
                                                        
Query OK, 1 row affected (0.00 sec)                     
                                                        
+----+-------+------+--------+--------+------------+    
| id | NAME  | age  | gender | cls_id | birth      |    
+----+-------+------+--------+--------+------------+    
|  1 | Tom   |   18 | male   |      1 | 1999-09-09 |    
|  2 | Jerry |   19 | male   |      1 | 1999-10-09 |    
|  3 | Nancy |   17 | male   |      2 | 1999-08-09 |    
+----+-------+------+--------+--------+------------+    
3 rows in set (0.00 sec)                                

枚举类型插入,下标是从1开始。

insert into students values(default,'John',19,1,1,'1999-7-9');
select * from students;

打印

Query OK, 1 row affected (0.00 sec)                  
                                                     
+----+-------+------+--------+--------+------------+ 
| id | NAME  | age  | gender | cls_id | birth      | 
+----+-------+------+--------+--------+------------+ 
|  1 | Tom   |   18 | male   |      1 | 1999-09-09 | 
|  2 | Jerry |   19 | male   |      1 | 1999-10-09 | 
|  3 | Nancy |   17 | male   |      2 | 1999-08-09 | 
|  4 | John  |   19 | male   |      1 | 1999-07-09 | 
+----+-------+------+--------+--------+------------+ 
4 rows in set (0.00 sec)                             

部分插入

非空字段必须要指定值,否则要指定默认值。

--insert into 表名(列1,...) values(值1,...)
insert into students(id,name,gender) values(default,'Tony',1);

打印

Query OK, 1 row affected (0.00 sec)

多行插入

insert into students values
(default,'John',19,1,2,'1999-7-9'),
(default,'Rose',19,2,2,'1999-7-9')
;

打印

Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

小编那么拼,赞一个再撤!
公众号二维码
大家也可以关注我的公众号:Python极客社区,在我的公众号里,经常会分享很多Python的文章,而且也分享了很多工具、学习资源等。另外回复“电子书”还可以获取十本我精心收集的Python电子书。

发布了51 篇原创文章 · 获赞 184 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/CUFEECR/article/details/103314886