日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

Mac操作数据库Mysql知识点备忘录

發(fā)布時(shí)間:2024/1/18 数据库 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Mac操作数据库Mysql知识点备忘录 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

目錄

Mac安裝Ubuntu啟動(dòng)Mysql

Mac安裝Mysql

CenterOS

Mac

Mysql 8和5的密碼插件區(qū)別

介紹

基礎(chǔ)命令操作數(shù)據(jù)庫

遠(yuǎn)程連接

數(shù)據(jù)庫操作命令

表操作命令

數(shù)據(jù)操作命令

備份與恢復(fù)命令

查詢分配

條件查詢

聚合查詢

分組查詢

排序

分頁查詢

高級(jí)特性

表關(guān)系建立和外鍵

inner join 連接查詢

完整的select語句

自關(guān)聯(lián)

視圖sql語句的封裝

事務(wù)

索引

小例子

Python3.6數(shù)據(jù)庫操作Demo

配置PYCharm

邏輯代碼

面向?qū)ο蠓庋b

登錄Demo


Mac安裝Ubuntu啟動(dòng)Mysql

1.先安裝VirtualBoxVM? ?安裝搜狗

2.然后安裝Ubuntu系統(tǒng)安裝

3.打開Ubuntu左側(cè)工具欄選擇軟件中心,搜索Mysql更新安裝Mysql客戶端和Mysql服務(wù)端源

4.執(zhí)行命令安裝

安裝

sudo apt-get install mysql-server mysql-client 然后按照提示輸入

一旦安裝完成,MySQL 服務(wù)器應(yīng)該自動(dòng)啟動(dòng)。您可以在終端提示符后運(yùn)行以下命令來檢查 MySQL 服務(wù)器是否正在運(yùn)行

sudo netstat -tap | grep mysql

出現(xiàn)如下代表已啟動(dòng)

deftmikejing@deftmikejing-VirtualBox:~$ sudo netstat -tap | grep mysql [sudo] password for deftmikejing: tcp6 0 0 [::]:mysql [::]:* LISTEN 1078/mysqld deftmikejing@deftmikejing-VirtualBox:~$ 或者 deftmikejing@deftmikejing-VirtualBox:/lib/systemd/system$ ps ajx|grep mysql1 686 686 686 ? -1 Ss 120 0:00 /bin/sh /usr/bin/mysqld_safe686 1141 686 686 ? -1 Sl 120 0:01 /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib/mysql/plugin --log-error=/var/log/mysql/error.log --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/run/mysqld/mysqld.sock --port=33062877 6341 6340 2877 pts/1 6340 S+ 1000 0:00 grep --color=auto mysql
  • 啟動(dòng)
service mysql start
  • 停止
service mysql stop
  • 重啟
service mysql restart

如果服務(wù)器不能正常運(yùn)行,您可以通過下列命令啟動(dòng)它:

?sudo /etc/init.d/mysql restart

mysql 的默認(rèn)密碼是linux系統(tǒng)密碼,如果需要修改

mysql -u root -p輸入密碼set password =password('需要替換的密碼');

5.設(shè)置mysql遠(yuǎn)程訪問

使用 sudo netstat -lntp 命令看看

tcp??????? 0????? 0 0.0.0.0:3306??????????? 0.0.0.0:*?????????????? LISTEN?
如果上面0 0.0.0.0后面不是3306的話就打開/etc/mysql/my.cnf?? 吧下面這一行給注釋掉

bind-address = 127.0.0.1

修改配置以后記得要重啟mysql

編輯mysql配置文件,把其中bind-address = 127.0.0.1注釋了

vi /etc/mysql/mysql.conf.d/mysqld.cnf

建立遠(yuǎn)程連接?

使用root進(jìn)入mysql命令行 mysql -uroot -p執(zhí)行如下2個(gè)命令,示例中mysql的root賬號(hào)密碼:root(這root填寫具體的密碼) grant all privileges on *.* to root@"%" identified by "password" with grant option; flush privileges;重啟mysql/etc/init.d/mysql restart

注意說明

本機(jī)登陸mysql:mysql -u root -p (-p一定要有);從所有主機(jī):grant all privileges on *.* to root@"%" identified by "password" with grant option;從指定主機(jī):grant all privileges on *.* to root@"192.168.11.205" identified by "password" with grant option;??例如:grant all privileges on *.* to test@'192.168.113.124' identified by '123456'然后執(zhí)行flush privileges;重啟Mysql

查看下剛才的賬號(hào)

select host,user,password from mysql.user

到這里就可以測(cè)試下宿主機(jī)器ping通宿主下的Ubuntu

默認(rèn)情況下無法ping通,需要修改網(wǎng)絡(luò)設(shè)置?參考鏈接

之后下載Navicat用Mac鏈接Ubuntu里面的Mysql就可以用圖形化工具操作了

Mac安裝Mysql

CenterOS

一般我們部署到Linux上去,這里就先介紹些CenterOS的安裝方法

以 MySQL 5.6 的 Yum 源為例,如果需要更高版本可以另尋,安裝命令如下:

wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm sudo rpm -ivh mysql-community-release-el7-5.noarch.rpm yum install -y mysql mysql-server

運(yùn)行如上命令即可完成安裝,初始密碼為空。接下來需要啟動(dòng) MySQL 服務(wù)。

啟動(dòng) MySQL 服務(wù)命令:

sudo systemctl start mysqld

停止、重啟命令:

sudo systemctl stop mysqld sudo systemctl restart mysqld

以上我們就完成了 Linux 下 MySQL 的安裝,安裝完成之后可以修改密碼,可以執(zhí)行如下命令:

mysql -uroot -p

輸入密碼后進(jìn)入 MySQL 命令行模式。

use mysql; UPDATE user SET Password = PASSWORD('newpass') WHERE user = 'root'; FLUSH PRIVILEGES;

命令中 newpass 即為修改的新的 MySQL 密碼,請(qǐng)自行替換。

由于 Linux 一般會(huì)作為服務(wù)器使用,為了使得 MySQL 可以被遠(yuǎn)程訪問,我們需要修改 MySQL 的配置文件,配置文件路徑一般為 /etc/mysql/my.cnf。

如使用 vi 進(jìn)行修改的命令如下:

vi /etc/mysql/my.cnf

取消此行的注釋:

bind-address = 127.0.0.1

此行限制了 MySQL 只能本地訪問而不能遠(yuǎn)程訪問,取消注釋即可解除此限制。

修改完成之后重啟 MySQL 服務(wù),這樣 MySQL 就可以被遠(yuǎn)程訪問了。

到此為止,Linux 下安裝 MySQL 的過程結(jié)束。

Mac

推薦使用 Homebrew 安裝,執(zhí)行 brew 命令即可。

brew install mysql

啟動(dòng)、停止、重啟 MySQL 服務(wù)的命令:

sudo mysql.server start sudo mysql.server stop sudo mysql.server restart

Mac 一般不會(huì)作為服務(wù)器使用,如果要想取消本地 host 綁定,同樣修改 my.cnf 文件,然后重啟服務(wù)即可。

?

這里如果找不到my.cnf文件,可以通過如下命令進(jìn)行查找:

find 文件路徑 參數(shù)

比如你可以通過以下命令在用戶文件夾中搜索名字中包含screen的文件

find ~ -iname ?"screen*"

你也可以在特定的文件夾中尋找特定的文件,比如

find ~/Library/ -iname "com.apple.syncedpreferences.plist"

這個(gè)命令可以在Library文件夾中尋找com.apple.syncedpreferences.plist文件

mdfind命令就是Spotlight功能的終端界面,這意味著如果Spotlight被禁用,mdfind命令也將無法工作。mdfind命令非常迅速、高效。最基本的使用方法是:

mdfind -name 文件名字

比如你可以通過下面的命令尋找Photo 1.PNG文件

mdfind -name "Photo 1.PNG"

因?yàn)閙dfind就是Spotlight功能的終端界面,你還可以使用mdfind尋找文件和文件夾的內(nèi)容,比如通過以下命令尋找所有包含Will Pearson文字的文件:

mdfind "Will Pearson"

mdfind命令還可以通過-onlyin參數(shù)搜索特定文件夾的內(nèi)容,比如

mdfind -onlyin ~/Library plist

這條命令可以搜索Library文件夾中所有plist文件。

mikejing$ mdfind -name "my.cnf" /usr/local/etc/my.cnf

修改該文件下127.0.0.1?是否注釋來調(diào)整是否可以遠(yuǎn)程連接。

安裝之后進(jìn)行配置

1.啟動(dòng)

mysql.server start

2.mysql配置腳本

/usr/local/opt/mysql/bin/mysql_secure_installation //mysql 提供的配置向?qū)?

詳細(xì)如下

sunyichaodeMacBook-Pro:~ sunyichao$ /usr/local/opt/mysql/bin/mysql_secure_installation //mysql 提供的配置向?qū)?Securing the MySQL server deployment. Connecting to MySQL using a blank password. VALIDATE PASSWORD PLUGIN can be used to test passwordsand improve security. It checks the strength of password and allows the users to set only those passwords which are secure enough. Would you like to setup VALIDATE PASSWORD plugin?Press y|Y for Yes, any other key for No: k //是否采用mysql密碼安全檢測(cè)插件(這里作為演示選擇否,密碼檢查插件要求密碼復(fù)雜程度高,大小寫字母+數(shù)字+字符等) Please set the password for root here. // 首次使用自帶配置腳本,設(shè)置root密碼New password:Re-enter new password:By default, a MySQL installation has an anonymous user, allowing anyone to log into MySQL without having to have a user account created for This is intended only for testing, and to make the installation go a bit smoother. You should remove them before moving into a production environment. Remove anonymous users? [Y/n] Y //是否刪除匿名用戶... Success!Normally, root should only be allowed to connect from 'localhost'.This ensures that someone cannot guess at the root password from the network.Disallow root login remotely? [Y/n] Y //是否禁止遠(yuǎn)程登錄... Success!By default, MySQL comes with a database named 'test' that anyone can access.This is also intended only for testing, and should be removed before moving into a production environment.Remove test database and access to it? [Y/n] Y //刪除測(cè)試數(shù)據(jù)庫,并登錄Dropping test database...... Success!Removing privileges on test database...... Success!Reloading the privilege tables will ensure that all changes made so far will take effect immediately.Reload privilege tables now? [Y/n] Y//重新載入權(quán)限表... Success!All done! If you've completed all of the above steps, your MySQL installation should now be secure.Thanks for using MySQL!Cleaning up... sunyichaodeMacBook-Pro:~ sunyichao$

Mysql 8和5的密碼插件區(qū)別

Navicat連接報(bào)錯(cuò)如下:

2059 - Authentication plugin 'caching_sha2_password' cannot be loaded: dlopen(../Frameworks/caching_sha2_password.so, 2): image not found

兩個(gè)版本的區(qū)別?

mysql> select version()-> ; +-----------+ | version() | +-----------+ | 8.0.16 | +-----------+ 1 row in set (0.01 sec)mysql> show variables like 'default_authentication_plugin'-> ; +-------------------------------+-----------------------+ | Variable_name | Value | +-------------------------------+-----------------------+ | default_authentication_plugin | caching_sha2_password | +-------------------------------+-----------------------+ 1 row in set (0.10 sec)mysql> show tables; +---------------------------+ | Tables_in_mysql | +---------------------------+ | columns_priv | | component | | db | | default_roles | | engine_cost | | func | | general_log | | global_grants | | gtid_executed | | help_category | | help_keyword | | help_relation | | help_topic | | innodb_index_stats | | innodb_table_stats | | password_history | | plugin | | procs_priv | | proxies_priv | | role_edges | | server_cost | | servers | | slave_master_info | | slave_relay_log_info | | slave_worker_info | | slow_log | | tables_priv | | time_zone | | time_zone_leap_second | | time_zone_name | | time_zone_transition | | time_zone_transition_type | | user | +---------------------------+ 33 rows in set (0.01 sec)mysql> select Host, User, Plugin from user; +-----------+------------------+-----------------------+ | Host | User | Plugin | +-----------+------------------+-----------------------+ | localhost | mysql.infoschema | caching_sha2_password | | localhost | mysql.session | caching_sha2_password | | localhost | mysql.sys | caching_sha2_password | | localhost | root | caching_sha2_password | +-----------+------------------+-----------------------+ 4 rows in set (0.00 sec) mysql> select version(); +------------+ | version() | +------------+ | 5.7.15-log | +------------+ 1 row in set (0.00 sec)mysql> show variables like 'default_authentication_plugin'; +-------------------------------+-----------------------+ | Variable_name | Value | +-------------------------------+-----------------------+ | default_authentication_plugin | mysql_native_password | +-------------------------------+-----------------------+ 1 row in set (0.01 sec)mysql> select host,user,plugin from mysql.user; +-----------+-----------+-----------------------+ | host | user | plugin | +-----------+-----------+-----------------------+ | localhost | root | mysql_native_password | | localhost | mysql.sys | mysql_native_password | | % | root | mysql_native_password |

可以看到MySQL8.0.11版本默認(rèn)的認(rèn)證方式是caching_sha2_password ,而在MySQL5.7版本則為mysql_native_password。

若想在MySQL8.0版本中繼續(xù)使用舊版本中的認(rèn)證方式需要在my.cnf 文件中配置并重啟,因?yàn)榇藚?shù)不可動(dòng)態(tài)修改。
?

mysql> set global default_authentication_plugin='mysql_native_password'; ERROR 1238 (HY000): Variable 'default_authentication_plugin' is a read only variable

寫入my.cnf 文件后重啟MySQL:

vim my.cnf [mysqld] default_authentication_plugin=mysql_native_password

上面的這種方案對(duì)已有的賬戶是無法修改的,只是后續(xù)新增的賬戶就會(huì)默認(rèn)的Plugin變成mysql_native_password?


第二種解決方法:兼容新老版本的認(rèn)證方式。

ALTER USER 'root'@'localhost' IDENTIFIED BY 'password' PASSWORD EXPIRE NEVER; #修改加密規(guī)則? ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password'; #更新一下用戶的密碼? FLUSH PRIVILEGES; #刷新權(quán)限

創(chuàng)建新用戶步驟,其中 with mysql_native_password不是必須的,默認(rèn)根據(jù)配置文件走?

--創(chuàng)建新的用戶:create user root@'%' identified WITH mysql_native_password BY 'password';grant all privileges on *.* to root@'%' with grant option;flush privileges;--在MySQL8.0創(chuàng)建用戶并授權(quán)的語句則不被支持:mysql> grant all privileges on *.* to root@'%' identified by 'password' with grant option;ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'identified by 'root' with grant option' at line 1mysql>

?

介紹

  • 數(shù)據(jù)庫系統(tǒng)解決的問題:持久化存儲(chǔ),優(yōu)化讀寫,保證數(shù)據(jù)的有效性
  • 當(dāng)前使用的數(shù)據(jù)庫,主要分為兩類
    • 文檔型,如sqlite,就是一個(gè)文件,通過對(duì)文件的復(fù)制完成數(shù)據(jù)庫的復(fù)制
    • 服務(wù)型,如mysql、postgre,數(shù)據(jù)存儲(chǔ)在一個(gè)物理文件中,但是需要使用終端以tcp/ip協(xié)議連接,進(jìn)行數(shù)據(jù)庫的讀寫操作

E-R模型

  • 當(dāng)前物理的數(shù)據(jù)庫都是按照E-R模型進(jìn)行設(shè)計(jì)的
  • E表示entry,實(shí)體
  • R表示relationship,關(guān)系
  • 一個(gè)實(shí)體轉(zhuǎn)換為數(shù)據(jù)庫中的一個(gè)表
  • 關(guān)系描述兩個(gè)實(shí)體之間的對(duì)應(yīng)規(guī)則,包括
    • 一對(duì)一
    • 一對(duì)多
    • 多對(duì)多
  • 關(guān)系轉(zhuǎn)換為數(shù)據(jù)庫表中的一個(gè)列 *在關(guān)系型數(shù)據(jù)庫中一行就是一個(gè)對(duì)象

三范式

  • 經(jīng)過研究和對(duì)使用中問題的總結(jié),對(duì)于設(shè)計(jì)數(shù)據(jù)庫提出了一些規(guī)范,這些規(guī)范被稱為范式
  • 第一范式(1NF):列不可拆分
  • 第二范式(2NF):唯一標(biāo)識(shí)
  • 第三范式(3NF):引用主鍵
  • 說明:后一個(gè)范式,都是在前一個(gè)范式的基礎(chǔ)上建立的

?

字段類型

  • 在mysql中包含的數(shù)據(jù)類型很多,這里主要列出來常用的幾種
  • 數(shù)字:int,decimal
  • 字符串:char(不可變,長(zhǎng)度不夠自動(dòng)填充), varchar(可變的),text
  • 日期:datetime
  • 布爾:bit


    約束
  • 主鍵primary key
  • 非空not null
  • 惟一unique
  • 默認(rèn)default
  • 外鍵foreign key

基礎(chǔ)命令操作數(shù)據(jù)庫

遠(yuǎn)程連接

  • 一般在公司開發(fā)中,可能會(huì)將數(shù)據(jù)庫統(tǒng)一搭建在一臺(tái)服務(wù)器上,所有開發(fā)人員共用一個(gè)數(shù)據(jù)庫,而不是在自己的電腦中配置一個(gè)數(shù)據(jù)庫
  • 運(yùn)行命令
mysql -hip地址 -uroot -p
  • -h后面寫要連接的主機(jī)ip地址
  • -u后面寫連接的用戶名
  • -p回車后寫密碼

數(shù)據(jù)庫操作命令

  • 查看數(shù)據(jù)庫
show databases;
  • 創(chuàng)建數(shù)據(jù)庫
create database 數(shù)據(jù)庫名 charset=utf8;
  • 刪除數(shù)據(jù)庫
drop database 數(shù)據(jù)庫名;
  • 切換數(shù)據(jù)庫
use 數(shù)據(jù)庫名;
  • 查看當(dāng)前選擇的數(shù)據(jù)庫
select database();

表操作命令

  • 查看當(dāng)前數(shù)據(jù)庫中所有表
show tables;
  • 創(chuàng)建表
  • auto_increment表示自動(dòng)增長(zhǎng)

    create table 表名(列及類型); 如: create table students( id int auto_increment primary key, sname varchar(10) not null );
  • 修改表

alter table 表名 add|change|drop 列名 類型; 如: alter table students add birthday datetime;change舉例alter table 表名 change 原字段 修改后字段 類型
  • 刪除表
drop table 表名;
  • 查看表結(jié)構(gòu)
desc 表名;
  • 更改表名稱
rename table 原表名 to 新表名;
  • 查看表的創(chuàng)建語句
show create table 表名;

數(shù)據(jù)操作命令

  • 查詢
select * from 表名
  • 增加
全列插入:insert into 表名 values(...) 缺省插入:insert into 表名(列1,...) values(值1,...) 同時(shí)插入多條數(shù)據(jù):insert into 表名 values(...),(...)...; 或insert into 表名(列1,...) values(值1,...),(值1,...)...;
  • 主鍵列是自動(dòng)增長(zhǎng),但是在全列插入時(shí)需要占位,通常使用0,插入成功后以實(shí)際數(shù)據(jù)為準(zhǔn)
  • 修改
update 表名 set 列1=值1,... where 條件
  • 刪除
delete from 表名 where 條件
  • 邏輯刪除,本質(zhì)就是修改操作update
alter table students add isdelete bit default 0; 如果需要?jiǎng)h除則 update students isdelete=1 where ...;

備份與恢復(fù)命令

數(shù)據(jù)備份

  • 進(jìn)入超級(jí)管理員
sudo -s
  • 進(jìn)入mysql庫目錄?
Homebrew 安裝目錄? /usr/local/var/mysql/ cd /usr/local/var/mysql/
  • 運(yùn)行mysqldump命令
mysqldump –uroot –p 數(shù)據(jù)庫名 > ~/Desktop/備份文件.sql; 按提示輸入mysql的密碼

數(shù)據(jù)恢復(fù)

  • 連接mysql,創(chuàng)建數(shù)據(jù)庫

  • 退出連接,執(zhí)行如下命令

mysql -uroot –p 數(shù)據(jù)庫名 < ~/Desktop/備份文件.sql 根據(jù)提示輸入mysql密碼

查詢分配

條件查詢

  • 查詢的基本語法
select * from 表名;
  • from關(guān)鍵字后面寫表名,表示數(shù)據(jù)來源于是這張表
  • select后面寫表中的列名,如果是*表示在結(jié)果中顯示表中所有列
  • 在select后面的列名部分,可以使用as為列起別名,這個(gè)別名出現(xiàn)在結(jié)果集中
  • 如果要查詢多個(gè)列,之間使用逗號(hào)分隔

消除重復(fù)行

  • 在select后面列前使用distinct可以消除重復(fù)的行
select distinct gender from students;
  • 使用where子句對(duì)表中的數(shù)據(jù)篩選,結(jié)果為true的行會(huì)出現(xiàn)在結(jié)果集中
  • 語法如下:
select * from 表名 where 條件;

比較運(yùn)算符

  • 等于=
  • 大于>
  • 大于等于>=
  • 小于<
  • 小于等于<=
  • 不等于!=或<>
  • 查詢編號(hào)大于3的學(xué)生
select * from students where id>3;
  • 查詢編號(hào)不大于4的科目
select * from subjects where id<=4;
  • 查詢姓名不是“黃蓉”的學(xué)生
select * from students where sname!='黃蓉';
  • 查詢沒被刪除的學(xué)生
select * from students where isdelete=0;

邏輯運(yùn)算符

  • and
  • or
  • not
  • 查詢編號(hào)大于3的女同學(xué)
select * from students where id>3 and gender=0;
  • 查詢編號(hào)小于4或沒被刪除的學(xué)生
select * from students where id<4 or isdelete=0;

模糊查詢

  • like
  • %表示任意多個(gè)任意字符
  • _表示一個(gè)任意字符
  • 查詢姓黃的學(xué)生
select * from students where sname like '黃%';
  • 查詢姓黃并且名字是一個(gè)字的學(xué)生
select * from students where sname like '黃_';
  • 查詢姓黃或叫靖的學(xué)生
select * from students where sname like '黃%' or sname like '%靖%';

范圍查詢

  • in表示在一個(gè)非連續(xù)的范圍內(nèi)
  • 查詢編號(hào)是1或3或8的學(xué)生
select * from students where id in(1,3,8);
  • between ... and ...表示在一個(gè)連續(xù)的范圍內(nèi)
  • 查詢學(xué)生是3至8的學(xué)生
select * from students where id between 3 and 8;
  • 查詢學(xué)生是3至8的男生
select * from students where id between 3 and 8 and gender=1;

空判斷

  • 注意:null與''是不同的
  • 判空is null
  • 查詢沒有填寫地址的學(xué)生
select * from students where hometown is null;
  • 判非空is not null
  • 查詢填寫了地址的學(xué)生
select * from students where hometown is not null;
  • 查詢填寫了地址的女生
select * from students where hometown is not null and gender=0;

優(yōu)先級(jí)

  • 小括號(hào),not,比較運(yùn)算符,邏輯運(yùn)算符
  • and比or先運(yùn)算,如果同時(shí)出現(xiàn)并希望先算or,需要結(jié)合()使用

聚合查詢

  • 為了快速得到統(tǒng)計(jì)數(shù)據(jù),提供了5個(gè)聚合函數(shù)
  • count(*)表示計(jì)算總行數(shù),括號(hào)中寫星與列名,結(jié)果是相同的
  • 查詢學(xué)生總數(shù)
select count(*) from students;
  • max(列)表示求此列的最大值
  • 查詢女生的編號(hào)最大值
select max(id) from students where gender=0;
  • min(列)表示求此列的最小值
  • 查詢未刪除的學(xué)生最小編號(hào)
select min(id) from students where isdelete=0;
  • sum(列)表示求此列的和
  • 查詢男生的編號(hào)之后
select sum(id) from students where gender=1;
  • avg(列)表示求此列的平均值
  • 查詢未刪除女生的編號(hào)平均值
select avg(id) from students where isdelete=0 and gender=0;

分組查詢

  • 按照字段分組,表示此字段相同的數(shù)據(jù)會(huì)被放到一個(gè)組中
  • 分組后,只能查詢出相同的數(shù)據(jù)列,對(duì)于有差異的數(shù)據(jù)列無法出現(xiàn)在結(jié)果集中
  • 可以對(duì)分組后的數(shù)據(jù)進(jìn)行統(tǒng)計(jì),做聚合運(yùn)算
  • 語法:
select 列1,列2,聚合... from 表名 group by 列1,列2,列3...
  • 查詢男女生總數(shù)
select gender as 性別,count(*) from students group by gender;
  • 查詢各城市人數(shù)
select hometown as 家鄉(xiāng),count(*) from students group by hometown;

分組后的數(shù)據(jù)篩選

  • 語法:
select 列1,列2,聚合... from 表名 group by 列1,列2,列3... having 列1,...聚合...
  • having后面的條件運(yùn)算符與where的相同
  • 查詢男生總?cè)藬?shù)
方案一 select count(*) from students where gender=1; ----------------------------------- 方案二: select gender as 性別,count(*) from students group by gender having gender=1;

對(duì)比where與having

  • where是對(duì)from后面指定的表進(jìn)行數(shù)據(jù)篩選,屬于對(duì)原始數(shù)據(jù)的篩選
  • having是對(duì)group by的結(jié)果進(jìn)行篩選

排序

  • 為了方便查看數(shù)據(jù),可以對(duì)數(shù)據(jù)進(jìn)行排序
  • 語法:
select * from 表名 order by 列1 asc|desc,列2 asc|desc,...
  • 將行數(shù)據(jù)按照列1進(jìn)行排序,如果某些行列1的值相同時(shí),則按照列2排序,以此類推
  • 默認(rèn)按照列值從小到大排列
  • asc從小到大排列,即升序
  • desc從大到小排序,即降序
  • 查詢未刪除男生學(xué)生信息,按學(xué)號(hào)降序
select * from students where gender=1 and isdelete=0 order by id desc;
  • 查詢未刪除科目信息,按名稱升序
select * from subject where isdelete=0 order by stitle;

分頁查詢

  • 當(dāng)數(shù)據(jù)量過大時(shí),在一頁中查看數(shù)據(jù)是一件非常麻煩的事情
  • 語法
select * from 表名 limit start,count
  • 從start開始,獲取count條數(shù)據(jù)
  • start索引從0開始

示例:分頁

  • 已知:每頁顯示m條數(shù)據(jù),當(dāng)前顯示第n頁
  • 求總頁數(shù):此段邏輯后面會(huì)在python中實(shí)現(xiàn)
    • 查詢總條數(shù)p1
    • 使用p1除以m得到p2
    • 如果整除則p2為總數(shù)頁
    • 如果不整除則p2+1為總頁數(shù)
  • 求第n頁的數(shù)據(jù)
select * from students where isdelete=0 limit (n-1)*m,m

高級(jí)特性

表關(guān)系建立和外鍵

案例一:

學(xué)生 1對(duì)多? 成績(jī)?? ? 學(xué)生表中一行能對(duì)應(yīng)多行成績(jī)出現(xiàn)

科目 1對(duì)多? 成績(jī)? ? 科目中一行能對(duì)應(yīng)多行成績(jī)出現(xiàn)

成績(jī) 1對(duì)1? ?學(xué)生和科目? ?一條成績(jī)必定對(duì)應(yīng)一個(gè)學(xué)生和一個(gè)科目

案例二:

班級(jí)? ? 1對(duì)多? 學(xué)生? ? 班級(jí)表中一行,能對(duì)應(yīng)多行學(xué)生出現(xiàn)

學(xué)生? 1對(duì)1? ? 班級(jí)? ? ? 一個(gè)學(xué)生必定對(duì)應(yīng)一個(gè)班級(jí)

1對(duì)多代表1的這一方會(huì)出現(xiàn)多個(gè)在另一方,因此主鍵關(guān)聯(lián)都會(huì)寫在學(xué)生表中或者成績(jī)表中?

  • 創(chuàng)建成績(jī)表scores,結(jié)構(gòu)如下
    • id
    • 學(xué)生
    • 科目
    • 成績(jī)
  • ?
  • 思考:學(xué)生列應(yīng)該存什么信息呢?
  • 答:學(xué)生列的數(shù)據(jù)不是在這里新建的,而應(yīng)該從學(xué)生表引用過來,關(guān)系也是一條數(shù)據(jù);根據(jù)范式要求應(yīng)該存儲(chǔ)學(xué)生的編號(hào),而不是學(xué)生的姓名等其它信息
  • 同理,科目表也是關(guān)系列,引用科目表中的數(shù)據(jù)

這里學(xué)生,成績(jī),科目三個(gè)的分析和電商里面 用戶,購(gòu)物車,商品是一樣的,首先

學(xué)生和科目是n:m的關(guān)系,無法維護(hù),因此需要再開一張表成績(jī)來維護(hù)好比用戶和商品是n:m的關(guān)系,因此需要購(gòu)物車來維護(hù),用戶和購(gòu)物車是1:n,商品和購(gòu)物車也是1:n

?

以下是科目和學(xué)生的標(biāo) 以及創(chuàng)建一張成績(jī)單的標(biāo),

+----+---------+ | id | title | +----+---------+ | 1 | Science | | 2 | Math | | 3 | English | | 4 | Pysical | | 5 | Mamical | +----+---------+ 5 rows in set (0.00 sec)mysql> select *from students; +----+------------+--------+---------------------+----------+-------+----------+ | id | name | gender | birthday | isDelete | score | address | +----+------------+--------+---------------------+----------+-------+----------+ | 1 | Mekejing | | 2018-01-01 00:00:00 | | 97 | NULL | | 2 | jiaojiao | | 2018-01-01 00:00:00 | | 55 | NULL | | 3 | elf | | 2018-01-01 00:00:00 | | 100 | shenzhen | | 4 | 11111 | | 2018-01-01 00:00:00 | | 60 | shenzhen | | 6 | 3333333 | | 2018-01-01 00:00:00 | | 77 | shenzhen | | 7 | wuke | | 0000-00-00 00:00:00 | | 80 | NULL | | 8 | Deft | | 2019-01-01 00:00:00 | | 32 | NULL | | 9 | jiaoBo | | 2001-01-01 00:00:00 | | 71 | NULL | | 10 | oojiaojiao | | 2001-01-01 00:00:00 | | 71 | NULL | +----+------------+--------+---------------------+----------+-------+----------+mysql> create table score(-> id int auto_increment primary key not null,-> score decimal(4,1),-> stuid int,-> subid int,-> foreign key(stuid) references students(id),-> foreign key(subid) references subjects(id))-> ; Query OK, 0 rows affected (0.02 sec)mysql> desc score; +-------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | score | decimal(4,1) | YES | | NULL | | | stuid | int(11) | YES | MUL | NULL | | | subid | int(11) | YES | MUL | NULL | | +-------+--------------+------+-----+---------+----------------+

查看原始的創(chuàng)建腳本

show create table score;| score | CREATE TABLE `score` (`id` int(11) NOT NULL AUTO_INCREMENT,`score` decimal(4,1) DEFAULT NULL,`stuid` int(11) DEFAULT NULL,`subid` int(11) DEFAULT NULL,PRIMARY KEY (`id`),KEY `stuid` (`stuid`),KEY `subid` (`subid`),CONSTRAINT `score_ibfk_1` FOREIGN KEY (`stuid`) REFERENCES `students` (`id`),CONSTRAINT `score_ibfk_2` FOREIGN KEY (`subid`) REFERENCES `subjects` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 |

可以看到stuid和subid都是關(guān)聯(lián)著各自表中的primary key

  • 思考:怎么保證關(guān)系列數(shù)據(jù)的有效性呢?任何整數(shù)都可以嗎?
  • 答:必須是學(xué)生表中id列存在的數(shù)據(jù),可以通過外鍵約束進(jìn)行數(shù)據(jù)的有效性驗(yàn)證
  • 為stuid添加外鍵約束

可以和上面一樣直接在創(chuàng)建表的時(shí)候創(chuàng)建外鍵約束,也可以alter添加

alter table scores add constraint stu_sco foreign key(stuid) references students(id);
  • 此時(shí)插入或者修改數(shù)據(jù)時(shí),如果stuid的值在students表中不存在則會(huì)報(bào)錯(cuò)
  • 在創(chuàng)建表時(shí)可以直接創(chuàng)建約束

外鍵的級(jí)聯(lián)操作)

例如刪除students里面的一個(gè)學(xué)生,那么score里面已經(jīng)有數(shù)據(jù)關(guān)聯(lián)上,如何處理?

  • 在刪除students表的數(shù)據(jù)時(shí),如果這個(gè)id值在scores中已經(jīng)存在,則會(huì)拋異常
  • 推薦使用邏輯刪除,還可以解決這個(gè)問題
  • 可以創(chuàng)建表時(shí)指定級(jí)聯(lián)操作,也可以在創(chuàng)建表后再修改外鍵的級(jí)聯(lián)操作
  • 語法
alter table scores add constraint stu_sco foreign key(stuid) references students(id) on delete cascade;
  • 級(jí)聯(lián)操作的類型包括:
    • restrict(限制):默認(rèn)值,拋異常
    • cascade(級(jí)聯(lián)):如果主表的記錄刪掉,則從表中相關(guān)聯(lián)的記錄都將被刪除
    • set null:將外鍵設(shè)置為空
    • no action:什么都不做

刪除約束

查看表建立語句| Table | Create Table | +-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | score | CREATE TABLE `score` (`id` int(11) NOT NULL AUTO_INCREMENT,`score` decimal(5,2) DEFAULT NULL,`stuid` int(11) DEFAULT NULL,`subid` int(11) DEFAULT NULL,PRIMARY KEY (`id`),KEY `subid` (`subid`),KEY `stu_sco` (`stuid`),CONSTRAINT `stu_sco` FOREIGN KEY (`stuid`) REFERENCES `students` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 |刪除約束 alter table score drop foreign key stu_sco;這時(shí)候就可以刪除級(jí)聯(lián)的表數(shù)據(jù)了,比如這個(gè)時(shí)候你刪除了students表的數(shù)據(jù),其他表有外鍵關(guān)聯(lián)也沒事,因?yàn)榧s束已經(jīng)解除了,但是這個(gè)時(shí)候你要添加約束,就會(huì)報(bào)錯(cuò),因?yàn)閿?shù)據(jù)已經(jīng)找不到了 alter table score add constraint stu_sco foreign key(stuid) references students(id); ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`mikejing`.`#sql-15650_18`, CONSTRAINT `stu_sco` FOREIGN KEY (`stuid`) REFERENCES `students` (`id`)) mysql> delete from score where id = 4; Query OK, 1 row affected (0.00 sec)mysql> alter table score add constraint stu_sco foreign key(stuid) references students(id); Query OK, 4 rows affected (0.05 sec) Records: 4 Duplicates: 0 Warnings: 0

?

  • 問:查詢每個(gè)學(xué)生每個(gè)科目的分?jǐn)?shù)
  • 分析:學(xué)生姓名來源于students表,科目名稱來源于subjects,分?jǐn)?shù)來源于scores表,怎么將3個(gè)表放到一起查詢,并將結(jié)果顯示在同一個(gè)結(jié)果集中呢?
  • 答:當(dāng)查詢結(jié)果來源于多張表時(shí),需要使用連接查詢
  • 關(guān)鍵:找到表間的關(guān)系,當(dāng)前的關(guān)系是
    • students表的id---scores表的stuid
    • subjects表的id---scores表的subid
  • 則上面問題的答案是:
select students.sname,subjects.stitle,scores.score from scores inner join students on scores.stuid=students.id inner join subjects on scores.subid=subjects.id;
  • 結(jié)論:當(dāng)需要對(duì)有關(guān)系的多張表進(jìn)行查詢時(shí),需要使用連接join

inner join 連接查詢

select *from score inner join students;

這是最基本的,如果score表10條和students表5條,因此在不加on條件下,組合起來是10*5=50條新的數(shù)據(jù)組合,然后根據(jù)on后面的組合篩選,比如下面的操作,id關(guān)聯(lián)到的,因此自關(guān)聯(lián)的表可以理解為 自身表?xiàng)l目的平方組合出來的數(shù)據(jù)進(jìn)行篩選即可
?

實(shí)際上就是多個(gè)表鏈接成一個(gè)大表

  • 連接查詢分類如下:
    • 表A inner join 表B:表A與表B匹配的行會(huì)出現(xiàn)在結(jié)果中
    • 表A left join 表B:表A與表B匹配的行會(huì)出現(xiàn)在結(jié)果中,外加表A中獨(dú)有的數(shù)據(jù),未對(duì)應(yīng)的數(shù)據(jù)使用null填充
    • 表A right join 表B:表A與表B匹配的行會(huì)出現(xiàn)在結(jié)果中,外加表B中獨(dú)有的數(shù)據(jù),未對(duì)應(yīng)的數(shù)據(jù)使用null填充
  • 在查詢或條件中推薦使用“表名.列名”的語法
  • 如果多個(gè)表中列名不重復(fù)可以省略“表名.”部分
  • 如果表的名稱太長(zhǎng),可以在表名后面使用' as 簡(jiǎn)寫名'或' 簡(jiǎn)寫名',為表起個(gè)臨時(shí)的簡(jiǎn)寫名稱
  • 查詢學(xué)生的姓名、平均分
select students.sname,avg(scores.score) from scores inner join students on scores.stuid=students.id group by students.sname;
  • 查詢男生的姓名、總分
select students.sname,avg(scores.score) from scores inner join students on scores.stuid=students.id where students.gender=1 group by students.sname;
  • 查詢科目的名稱、平均分
select subjects.stitle,avg(scores.score) from scores inner join subjects on scores.subid=subjects.id group by subjects.stitle;
  • 查詢未刪除科目的名稱、最高分、平均分
select subjects.stitle,avg(scores.score),max(scores.score) from scores inner join subjects on scores.subid=subjects.id where subjects.isdelete=0 group by subjects.stitle;
  • 嵌套查詢
    第一個(gè)select from用的后面查詢出來的表,需要給一個(gè)as別名,不然會(huì)報(bào)錯(cuò)
select sum(anum) from (select students.name,sum(score.score) as anum from score inner join students on score.stuid=students.id where gender=1 group by students.name) as MKJ;

完整的select語句

select distinct * from 表名 inner |left|right|on join 表 on 關(guān)系 where .... group by ... having ... order by ... limit star,count
  • 執(zhí)行順序?yàn)?#xff1a;
    • from 表名
    • where .... inner...
    • group by ...
    • select distinct *
    • having ...
    • order by ...
    • limit star,count
  • 實(shí)際使用中,只是語句中某些部分的組合,而不是全部

自關(guān)聯(lián)

以省市縣為例,這些數(shù)據(jù)不需要開多個(gè)表,可以通過自關(guān)聯(lián)的方式完成,例如

id title pid 1 浙江 NULL 2 寧波 1(關(guān)聯(lián)到自身表中另一行) 3 慈溪 2 (關(guān)聯(lián)到自身表中另一行) 。。。。。

這種設(shè)計(jì)還有類似分類,一張表中可以無限數(shù)據(jù),無限分類下去,充分利用空間?

?

  • 設(shè)計(jì)省信息的表結(jié)構(gòu)provinces
    • id
    • ptitle
  • 設(shè)計(jì)市信息的表結(jié)構(gòu)citys
    • id
    • ctitle
    • proid
  • citys表的proid表示城市所屬的省,對(duì)應(yīng)著provinces表的id值
  • 問題:能不能將兩個(gè)表合成一張表呢?
  • 思考:觀察兩張表發(fā)現(xiàn),citys表比provinces表多一個(gè)列proid,其它列的類型都是一樣的
  • 意義:存儲(chǔ)的都是地區(qū)信息,而且每種信息的數(shù)據(jù)量有限,沒必要增加一個(gè)新表,或者將來還要存儲(chǔ)區(qū)、鄉(xiāng)鎮(zhèn)信息,都增加新表的開銷太大
  • 答案:定義表areas,結(jié)構(gòu)如下
    • id
    • atitle
    • pid
  • 因?yàn)槭]有所屬的省份,所以可以填寫為null
  • 城市所屬的省份pid,填寫省所對(duì)應(yīng)的編號(hào)id
  • 這就是自關(guān)聯(lián),表中的某一列,關(guān)聯(lián)了這個(gè)表中的另外一列,但是它們的業(yè)務(wù)邏輯含義是不一樣的,城市信息的pid引用的是省信息的id
  • 在這個(gè)表中,結(jié)構(gòu)不變,可以添加區(qū)縣、鄉(xiāng)鎮(zhèn)街道、村社區(qū)等信息
  • 創(chuàng)建areas表的語句如下:
create table areas( id int primary key, atitle varchar(20), pid int, foreign key(pid) references areas(id) );

視圖sql語句的封裝

  • 對(duì)于復(fù)雜的查詢,在多次使用后,維護(hù)是一件非常麻煩的事情
  • 解決:定義視圖
  • 視圖本質(zhì)就是對(duì)查詢的一個(gè)封裝
  • 定義視圖
create view stuscore as select students.*,scores.score from scores inner join students on scores.stuid=students.id;
  • 視圖的用途就是查詢
select * from stuscore;

事務(wù)

數(shù)據(jù)被更改時(shí)? insert? update delete?

  • 當(dāng)一個(gè)業(yè)務(wù)邏輯需要多個(gè)sql完成時(shí),如果其中某條sql語句出錯(cuò),則希望整個(gè)操作都退回
  • 使用事務(wù)可以完成退回的功能,保證業(yè)務(wù)邏輯的正確性
  • 事務(wù)四大特性(簡(jiǎn)稱ACID)
    • 原子性(Atomicity):事務(wù)中的全部操作在數(shù)據(jù)庫中是不可分割的,要么全部完成,要么均不執(zhí)行
    • 一致性(Consistency):幾個(gè)并行執(zhí)行的事務(wù),其執(zhí)行結(jié)果必須與按某一順序串行執(zhí)行的結(jié)果相一致
    • 隔離性(Isolation):事務(wù)的執(zhí)行不受其他事務(wù)的干擾,事務(wù)執(zhí)行的中間結(jié)果對(duì)其他事務(wù)必須是透明的
    • 持久性(Durability):對(duì)于任意已提交事務(wù),系統(tǒng)必須保證該事務(wù)對(duì)數(shù)據(jù)庫的改變不被丟失,即使數(shù)據(jù)庫出現(xiàn)故障
  • 要求:表的類型必須是innodb或bdb類型,才可以對(duì)此表使用事務(wù)
  • 查看表的創(chuàng)建語句
show create table students;
  • 修改表的類型
alter table '表名' engine=innodb;
  • 事務(wù)語句
開啟begin; 提交commit; 回滾rollback;

事務(wù)可以理解為對(duì)同一個(gè)東西的修改操作,可以理解為OC里面的setter操作,多線程會(huì)搶資源,因此會(huì)有鎖的存在,事務(wù)也是一樣,通過鎖來保證數(shù)據(jù)執(zhí)行的一致性和隔離性,事務(wù)其實(shí)就通過鎖在內(nèi)存中開辟一個(gè)空間進(jìn)行計(jì)算,通過commit或者rollback來確定是否需要采用之前的修改,如果其他線程也在操作數(shù)據(jù)庫而且是操作同一條,就會(huì)出現(xiàn)鎖等待,等commit或者rollback之后解鎖繼續(xù)執(zhí)行

先做個(gè)淺顯的理解,到時(shí)候深入了再來記錄;

其實(shí)事務(wù)可以優(yōu)化的點(diǎn)想到一個(gè),比如你要插入很多條數(shù)據(jù),直接執(zhí)行insert語句不開啟事務(wù),其實(shí)每次都會(huì)對(duì)數(shù)據(jù)庫的更改和提交操作,因此開啟事務(wù),再合理內(nèi)存配置范圍內(nèi),通過事務(wù)一次性提交更改物理數(shù)據(jù)庫,減少損耗

事務(wù)引擎提交事務(wù)會(huì)開啟行級(jí)鎖

索引

Mysql 索引原理

Mysql索引使用方式介紹

MySQL官方對(duì)索引的定義為:索引(Index)是幫助MySQL高效獲取數(shù)據(jù)的數(shù)據(jù)結(jié)構(gòu)。提取句子主干,就可以得到索引的本質(zhì):索引是數(shù)據(jù)結(jié)構(gòu)。

我們知道,數(shù)據(jù)庫查詢是數(shù)據(jù)庫的最主要功能之一。我們都希望查詢數(shù)據(jù)的速度能盡可能的快,因此數(shù)據(jù)庫系統(tǒng)的設(shè)計(jì)者會(huì)從查詢算法的角度進(jìn)行優(yōu)化。最基本的查詢算法當(dāng)然是順序查找(linear search),這種復(fù)雜度為O(n)的算法在數(shù)據(jù)量很大時(shí)顯然是糟糕的,好在計(jì)算機(jī)科學(xué)的發(fā)展提供了很多更優(yōu)秀的查找算法,例如二分查找(binary search)、二叉樹查找(binary tree search)等。如果稍微分析一下會(huì)發(fā)現(xiàn),每種查找算法都只能應(yīng)用于特定的數(shù)據(jù)結(jié)構(gòu)之上,例如二分查找要求被檢索數(shù)據(jù)有序,而二叉樹查找只能應(yīng)用于二叉查找樹上,但是數(shù)據(jù)本身的組織結(jié)構(gòu)不可能完全滿足各種數(shù)據(jù)結(jié)構(gòu)(例如,理論上不可能同時(shí)將兩列都按順序進(jìn)行組織),所以,在數(shù)據(jù)之外,數(shù)據(jù)庫系統(tǒng)還維護(hù)著滿足特定查找算法的數(shù)據(jù)結(jié)構(gòu),這些數(shù)據(jù)結(jié)構(gòu)以某種方式引用(指向)數(shù)據(jù),這樣就可以在這些數(shù)據(jù)結(jié)構(gòu)上實(shí)現(xiàn)高級(jí)查找算法。這種數(shù)據(jù)結(jié)構(gòu),就是索引。

可以理解為數(shù)據(jù)本身的組織結(jié)構(gòu)不可能滿足各種數(shù)據(jù)結(jié)構(gòu),比如滿足有序的二分查找或者二叉樹查找,因此需要建立索引,把該字段或者多個(gè)字段下的所有數(shù)據(jù)都拉出來新建一個(gè)目錄,滿足數(shù)據(jù)結(jié)構(gòu)查找,比如有序拉出來二分查找。

選擇數(shù)據(jù)類型

  • 越小的數(shù)據(jù)類型和簡(jiǎn)單的數(shù)據(jù)類型越好,數(shù)據(jù)越小磁盤,內(nèi)存,CPU中需要更少的空間,處理起來更快
  • 盡量避免NULL:應(yīng)指定列為NOT NULL,除非你想存儲(chǔ)NULL,在Mysql中,含有空值的列很難進(jìn)行查詢優(yōu)化,因?yàn)樗麄兪顾饕y(tǒng)計(jì)信息比較起來更復(fù)雜,應(yīng)該用0,特殊的值,或者空串來標(biāo)識(shí)

?

普通索引

普通索引僅有一個(gè)功能:加速查詢

創(chuàng)建表

create table in1(nid int not null auto_increment primary key,name varchar(32) not null,email varchar(64) not null,extra text,index ix_name (name) )

創(chuàng)建

create index index_name on table_name(column_name)

查看

show index from table_name;

刪除

drop index_name on table_name;

注意:對(duì)于創(chuàng)建索引時(shí)如果是BLOB?和?TEXT?類型,必須指定length。

create index ix_extra on in1(extra(32));

缺點(diǎn)

雖然索引提高了查詢速度,但是會(huì)降低更新表的速度,如果對(duì)表進(jìn)行INSERT UPDATE和DELETE,Mysql不僅要更新數(shù)據(jù),還有保存更新索引文件,而且建立索引會(huì)占磁盤索引對(duì)應(yīng)的文件

- 查看執(zhí)行時(shí)間set profiling = 1;SQL...show profiles;

詳細(xì)介紹可以看上面的文章

?

小例子

1、設(shè)計(jì)班級(jí)表,與學(xué)生表關(guān)聯(lián),并進(jìn)行查詢 2、設(shè)計(jì)分類表,自關(guān)聯(lián),并進(jìn)行查詢 3、創(chuàng)建視圖存儲(chǔ)上面的兩個(gè)查詢# 班級(jí)表和學(xué)生表關(guān)聯(lián) 1.班級(jí)表和學(xué)生表 班級(jí)表一條數(shù)據(jù)可以對(duì)應(yīng)多條學(xué)生數(shù)據(jù) 1:n 因此關(guān)聯(lián)外鍵設(shè)置在n這里 create table Class( id int auto_increment primary key not null, name varchar(10));create table Student( id int auto_increment primary key not null, name varchar(10), clsid int, foreign key(clsid) references Class(id));create view V_stu_class as select Student.id,Student.name,Class.name as className from Student inner join Class on Student.clsid=Class.id# 自關(guān)聯(lián) create table typeClass( id int auto_increment primary key not null, name varchar(10), pid int, foreign key(pid) references typeClass(id));create view V_types as select son.* from typeClass as father inner join TypeClass as son on son.pid=father.id

?

Python3.6數(shù)據(jù)庫操作Demo

首先Python3x之后需要安裝 pymysql

In [1]: import osIn [2]: os.__file__ Out[2]: '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/os.py'In [3]:

以上目錄能找到自帶的安裝包,我們執(zhí)行

pip3 install pymysql

可以在該目錄下找到site-packages文件夾,里面有我們自行安裝的所有安裝包,我們?cè)赾md下面import會(huì)在該目錄下自動(dòng)查找,OK

配置PYCharm

但是我們用PYCharm的時(shí)候,你import你自行安裝的包,是會(huì)報(bào)錯(cuò)的,告訴我們找不到該moduel,由于上不了圖了,說下步驟

1.打開PYCharm,File? ------ Default Settings---------選擇Project Interpreter,右側(cè)會(huì)出現(xiàn)默認(rèn)的配置環(huán)境

2.由于默認(rèn)的環(huán)境不會(huì)加載site-packages,需要自己配置新的,點(diǎn)擊齒輪,選擇Add

3.這里的彈出框默認(rèn)值不用管,只要把下面的Inherit global site-packages選上,第三方包就出現(xiàn)了

4.編譯的時(shí)候右上角會(huì)出現(xiàn)對(duì)應(yīng)的文件名選項(xiàng),點(diǎn)擊Edit Configuration選擇對(duì)應(yīng)的環(huán)境即可

以下是配置好之后的代碼

邏輯代碼

import pymysqlconfig = {'host':'192.168.0.61','port':3306,'user':'root','password':'mikejing','db':'python','charset':'utf8' } # 鏈接打開數(shù)據(jù)庫 db = pymysql.connect(**config)# 使用cousor() 創(chuàng)建一個(gè)游標(biāo)對(duì)象 cursor cursor = db.cursor()# 使用excute執(zhí)行sql語句 cursor.execute("SELECT VERSION()")# 使用fetchone獲取單條數(shù)據(jù) data = cursor.fetchone() print("Database version:%s"%data)# sql = "insert into students (name) values('握草')" # sql = "update students set name='框要是' where id=12" # sql = "delete from students where id=12" # data = input("請(qǐng)輸入姓名:") # sql = "insert into students (name) values(%s)" # cursor.execute(sql, data)sql = "select * from students where id=13" cursor.execute(sql) info = cursor.fetchone() print(info)sql = "select * from students" cursor.execute(sql) info1 = cursor.fetchall() print(info1)try:cursor.execute("show tables") except Exception as result:print(result)print(cursor.fetchall())name =input("請(qǐng)輸入修改后的名字:") ids = input("請(qǐng)輸入修改用戶ID:") params = [name,ids] sql = "update students set name=%s where id=%s" cursor.execute(sql,params)# 默認(rèn)開啟事務(wù),需要提交 db.commit() cursor.close() # 關(guān)閉數(shù)據(jù)庫 db.close()

面向?qū)ο蠓庋b

對(duì)象

import pymysqlclass MysqlHelper(object):def __init__(self,host, port, user, password, db, charset='utf8'):self.host = hostself.port = portself.user = userself.password = passwordself.db = dbself.charset = charsetdef connect(self):self.con = pymysql.connect(host=self.host,port=self.port,user=self.user,password=self.password,db=self.db,charset=self.charset)self.cursor = self.con.cursor()def dealloc(self):self.con.close()self.cursor.close()def cud(self, sql, params):try:self.connect()self.cursor.execute(sql,params)self.con.commit()self.dealloc()except Exception as result:print(result)def watch(self, sql, params=[]):try:self.connect()self.cursor.execute(sql,params)result = self.cursor.fetchall()self.con.commitself.dealloc()return resultexcept Exception as result:print("error:%s"%result)

使用

import MysqlHelperhelper = MysqlHelper.MysqlHelper('192.168.0.61', 3306, 'root', 'mikejing', 'python')name = input("請(qǐng)輸入修改后的名字:") ids = input("請(qǐng)輸入需要修改的用戶id:") params = (name, ids) sql = "update students set name=%s where id=%s"# 或者直接憑借 # sql = "update students set name=%s where id=%s"%(name, ids)helper.cud(sql, params)sql = "select * from students where id >20" result = helper.watch(sql) print(result)/Users/mintou/venv/bin/python /Users/mintou/Desktop/PYCharm/tPython.py 請(qǐng)輸入修改后的名字:29歲翻倍 請(qǐng)輸入需要修改的用戶id:30 ((24, 'hehehe', b'\x00', datetime.datetime(1990, 1, 1, 0, 0), b'\x00', 100, 'cixi', 'www.ads.com'), (25, '我是神e', b'\x00', datetime.datetime(1990, 1, 1, 0, 0), b'\x00', 100, 'cixi', 'www.ads.com'), (26, 'iOS大神', b'\x00', datetime.datetime(1990, 1, 1, 0, 0), b'\x00', 100, 'cixi', 'www.ads.com'), (27, '宓珂璟', b'\x01', None, b'\x00', None, None, None), (28, 'python大神', b'\x01', None, b'\x00', None, None, None), (30, '29歲翻倍', b'\x01', None, b'\x00', None, None, None))Process finished with exit code 0

登錄Demo

還是用上面的MysqlHelper工具 用sha1試試

正常登錄是RSA,用戶在客戶端輸入密碼,通過公鑰加密給后臺(tái),后臺(tái)私鑰解密,加鹽之后然后AES,接著存入數(shù)據(jù)庫,就是注冊(cè)

下次登錄的時(shí)候,輸入用戶名密碼,輸入密碼,公鑰加密,后臺(tái)私鑰解密,然后根據(jù)用戶名去數(shù)據(jù)庫select,匹配上就登錄成功

import MysqlHelper import hashlibhelper = MysqlHelper.MysqlHelper('192.168.0.61', 3306, 'root', 'mikejing', 'python')def sha1Operation(pwd):hash_pwd = pwd.encode("utf-8")hashTool = hashlib.sha1()hashTool.update(hash_pwd)return hashTool.hexdigest()print("注冊(cè)用戶密碼") name = input("name:") pwd = input("pwd:") parmes = (name,sha1Operation(pwd)) sql = "insert into userinofs values(0,%s,%s)" helper.cud(sql, parmes)print("*"*50+"注冊(cè)成功" + "*"*50)while True:print("登錄")name = input("name:")pwd = input("pwd:")parames = (name)sql = "select pwd from userinofs where username = %s"result = helper.watch(sql, parames)if len(result) == 0:print("用戶名不存在")elif result[0][0] == sha1Operation(pwd):print("登錄成功")break;else:print("密碼錯(cuò)誤")

?

?

參考文章

Python3各種模塊安裝(比如Mysql)

Mysql安裝初始化

find命令

總結(jié)

以上是生活随笔為你收集整理的Mac操作数据库Mysql知识点备忘录的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。