數據庫是一個存儲數據的倉庫,主要用在:金融機構、遊戲網站、購物網站、論壇網站,如今的主流數據庫有:MySQL、SQL_Server、Oracle、Mariadb、DB二、MongoDB ...php
那麼咱們在生產環境中,如何選擇使用哪一個數據庫html
1. 是否開源java
2. 是否跨平臺mysql
3. 公司的類型git
關係型數據庫,關係型數據庫的特色github
關係型數據庫存儲:二維表正則表達式
姓名 | 年齡 | 班級 |
牛郎 | 25 | AID1803 |
織女 | 23 | AID1801 |
二、非關係型數據庫中存儲:鍵值對 {"姓名":"牛郎","年齡":25,"班級":"AID1803","班主任":"盧大大"}sql
跨平臺:能夠在Unix、Linux、Windows上運行數據庫服務
支持多種編程語言:Python、java、php ... ...數據庫
Ubuntu安裝MySQL服務 RedHat(紅帽)、CentOS、Ubuntuexpress
Windows安裝MySQL服務
最好安裝MSI版本,不要裝逼去安裝解壓包,你本身又不會調。
1. 服務端啓動
查看MySQL服務狀態:sudo /etc/init.d/mysql status
中止、啓動、重啓MySQL服務:sudo /etc/init.d/mysql stop | start | restart
2. 客戶端鏈接
mysql -h主機地址 -u用戶名 -p密碼
mysql -hlocalhost -uroot -p123456
本地鏈接能夠省略 -h 選項
mysql -u用戶名 -p密碼
mysql -uroot -p123456
3. 退出
exit 或者 ctrl+Z 或者 ctrl+D
每條SQL命令必須以分號;結尾, SQL命令關鍵字不區分字母大小寫, 使用 \c 來終止命令的執行 (Linux中 ctrl + c), 全部的數據都是以文件的形式存放在數據庫目錄下, 數據庫目錄:/var/lib/mysql
查看已有的庫:show databases;
建立庫(指定字符集):create database 庫名 [character set utf8];
e.g. 建立stu數據庫,編碼爲utf8
create database stu character set utf8;
create database stu charset=utf8;
查看建立庫的語句(字符集):show create database 庫名;
e.g. 查看stu建立方法:show create database stu;
查看當前所在庫:select database();
切換庫:use 庫名;
e.g. 使用stu數據庫:use stu;
刪除庫:drop database 庫名;
刪除test數據庫:drop database test;
庫名的命名規則
1. 表結構設計初步
2. 數據類型
字符串類型:
char 和 varchar
text 和blob
enum 和 set
建立表(指定字符集)
create table 表名(
字段名 數據類型,
字段名 數據類型,
......
字段名 數據類型);
mysql> create table class(id int PRIMARY KEY AUTO_INCREMENT, -> name VARCHAR(32) NOT NULL, -> age int NOT NULL, -> sex ENUM("w", "m"), -> score float default 0.0); mysql> create table interest( -> id int primary key auto_increment, -> name varchar(32) not null, -> hobby set("sing", "dance", "draw"), -> price decimal(7,2), -> level char not null, -> comment text);
查看數據表 show tables;
查看已有表的字符集 show create table 表名;
查看錶結構 desc 表名;
刪除表 drop table 表名;
insert into 表名 values (記錄1),(記錄2),...; insert into 表名(字段1,字段2...) values(記錄1),...;
insert into class_1 values (2,'Baron',10,'m',91),(3,'Jame',9,'m',90);
select * from 表名 [where 條件];
select 字段1,字段名2 from 表名 [where 條件];
select * from class_1; select name,age from class_1;
where子句在sql語句中扮演了重要角色,主要經過必定的運算條件進行數據的篩選
MySQL 主要有如下幾種運算符:
運算符 | 做用 |
+ | 加法 |
- | 減法 |
* | 乘法 |
/ 或 DIV | 除法 |
% 或 MOD | 取餘 |
select * from class_1 where age % 2 = 0;
符號 | 描述 |
= | 等於 |
<>,!= | 不等 |
> | 大於 |
< | 小於 |
<= | 小於等於 |
>= | 大於等於 |
between 10 and 20 | 在10-20兩值之間 |
not betwen 10 and 20 | 不在10-20兩值之間 |
in (16,17) | 在集合(16,17) |
not in (16,17) | 不在集合(16,17) |
<=> | 嚴格比較兩個null值是否相等 |
link | 模糊匹配 |
regexp 或 rlike | 正則匹配 |
is null | 爲空 |
is not null | 不爲空 |
select * from class_1 where age > 8; select * from class_1 where between 8 and 10; select * from class_1 where age in (8,9);
運算符號 | 做用 |
not 或 1 | 邏輯非 |
and | 邏輯與 |
or | 邏輯或 |
xor | 邏輯異或 |
select * from class_1 where sex='m' and age>9;
練習:
1. 建立收據庫 grade
create database grade charset=utf8;
2. 數據庫中建立表 student
3. 表字段以下:id name age hobby score comment
mysql> use grade; mysql> create table student ( -> id int primary key auto_increment, -> name varchar(32), -> age int, -> hobby set('football','basketball','computer','running'), -> score float, -> comment text);
4. 插入若干收據
insert student into values (1,"小高",8,"basketball,computer",87.5,"OK"); insert student into values (2,"小紅",8,"football",87.5,"OK"); insert student into values (3,"小明",16,"running",90,"OK"); insert student into values (2,"小亮",8,"computer",64.7,"OK");
5.查找
update 表名 set 字段1=值1,字段2=值2,... where 條件;
update class_1 set age=11 where name='Abby';
delete from 表名 where 條件;
注意: delete語句後若是不加where條件,全部記錄所有清空
delete from class_1 where name='Abby';
語法 : alter table 表名 執行動做;
* 添加字段(add)
alter table 表名 add 字段名 數據類型;
alter table 表名 add 字段名 數據類型 first; # 增長到第一個位置
alter table 表名 add 字段名 數據類型 after 字段名; # 增長到某一個字段名後面
alter table interest add data cha(10); alter table interest add data cha(10) first; alter table interest add date Date cha(10) after course;
* 刪除字段(drop)
alter table 表名 drop 字段名;
* 修改字段類型(modify)
alter table 表名 modify 字段名 新數據類型;
* 修改字段名(change)
alter table 表名 change 舊字段名 新字段名 新數據類型;
alter table class change sex gender enum("m","w");
* 表 重命名(rename)
alter table 表名 rename 新表名;
alter table class rename chass_1;
類型 | 大小 (字節) |
格式 | 用途 |
---|---|---|---|
date | 3 | YYYY-MM-DD | 日期值 |
time | 3 | HH:MM:SS | 時間值或持續時間 |
year | 1 | YYYY | 年份值 |
datetime | 8 | YYYY-MM-DD HH:MM:SS | 混合日期和時間值 |
timestamp | 4 | YYYY-MM-DD HH:MM:SS | 混合日期和時間值,時間戳 |
注意
日期時間函數
查找操做
select * from timelog where Date = "2018-07-02"; select * from timelog where Date>="2018-07-01" and Date<="2018-07-31";
日期時間運算
select * from 表名 where 字段名 運算符 (時間-interval 時間間隔單位);
時間間隔單位: 1 day | 2 hour | 1 minute | 2 year | 3 month
# 一天前的數據 select * from timelog where shijian > (now()-interval 1 day);
模糊查詢和正則查詢
like用於在where子句中進行模糊查詢, SQL like 子句中使用百分號 %字符來表示任意字符。
使用 like 子句從數據表中讀取數據的通用語法:
select field1, field2,...fieldN from table_name where field1 like condittion1
mysql> select * from class_1 where name like 'A%';
mysql中對正則表達式的支持有限,只支持部分正則元字符
select field1, field2,...fieldN from table_name where field1 regexp condition1
e.g.
select * from class_1 where name regexp 'B.+';
排序
order by 子句來設定你想按哪一個字段哪一種方式來進行排序,再返回搜索結果。
使用 order by 子句將查詢數據排序後再返回數據:
select field1, field2,...fieldN from table_name1 where field1 order by field1 [ASC [DESC]]
默認狀況ASC表示升序,DESC表示降序
select * from class_1 where sex='m' order by age;
分頁
limit 子句用於限制由 select 語句返回的數據數量 或者 update, delete語句的操做數量帶有 limit 子句的 select 語句的基本語法以下:
select column1, column2, columnN from table_name where field limit [num]
聯合查詢
union 操做符用於鏈接兩個以上的 select 語句的結果組合到一個結果集合中。多個 select 語句會刪除重複的數據。union 操做符語法格式:
select expression1,... expression_n from tables [where conditions] union [all | distinct] select expression1,... expression_n from tables [where conditions];
expression1, expression2, ... expression_n: 要檢索的列。
tables: 要檢索的數據表。
where conditions: 可選, 檢索條件。
distinct: 可選,刪除結果集中重複的數據。默認狀況下 union 操做符已經刪除了重複數據, 因此 distinct 修飾符對結果沒啥影響。
all: 可選,返回全部結果集,包含重複數據。
要求查詢的字段必須相同
select * from class_1 where sex='m' UNION ALL select * from class_1 where age > 9;
多表查詢
多個表數據能夠聯合查詢,語法格式以下
select 字段1,字段2... from 表1,表2... [where 條件]
select class_1.name,class_1.age,class_1.sex,interest.hobby from class_1,interest where class_1.
1. 備份命令格式
mysqldump -u用戶名 -p 源庫名 > ~/***.sql
--all-databases 備份全部庫
庫名 備份單個庫
-B 庫1 庫2 庫3 備份多個庫
庫名 表1 表2 表3 備份指定庫的多張表
2. 恢復命令格式
mysql -uroot -p 目標庫名 < ***.sql
從全部庫備份中恢復某一個庫(--one-database)
mysql -uroot -p --one-database 目標庫名 < all.sql
pymysql安裝:pip install pymysql
使用pymysql以前都要手動的建立數據庫,以及表.
db = pymysql.connect(參數列表)
參數:
數據庫鏈接對象(db)的方法
遊標(cursor)的方法
寫數據
import pymysql # 鏈接數據庫 db = pymysql.connect(host='localhost', port=3306, user='root', password='123456', database='stu', charset='utf8') cur = db.cursor() # 獲取遊標(操做數據庫,執行sql語句) sql = "insert into class_1 values (7,'Emma',17,'w',76.5,'2019-8-8');" # 執行sql語句 cur.execute(sql) # 執行sql語句 db.commit() # 將"寫操做"一同提交;讀操做不用提交 cur.close() # 關閉浮標 db.close() # 關閉數據庫
查詢數據(讀數據)
import pymysql # 鏈接數據庫 db = pymysql.connect(host='localhost', port=3306, user='root', password='123456', database='stu', charset='utf8') cur = db.cursor() # 獲取遊標 (操做數據庫,執行sql語句) # 獲取數據庫數據 sql = "select name,age from class_1 where gender='m';" cur.execute(sql) # 執行正確後cur調用函數獲取結果 one_row = cur.fetchone() # 獲取一個查詢結果 print(one_row) # 元組 many_row = cur.fetchmany(2) # 獲取2個查詢結果 print(many_row) all_row = cur.fetchall() # 獲取全部查詢結果 print(all_row) cur.close() # 關閉遊標 db.close() # 關閉數據庫
二進制文件存儲
import pymysql # 鏈接數據庫 db = pymysql.connect(host='localhost', port=3306, user='root', password='123456', database='stu', charset='utf8') cur = db.cursor() # 獲取遊標 (操做數據庫,執行sql語句) # 存儲圖片 # with open('image.jpg','rb') as f: # data = f.read() # try: # sql = "update class_1 set image = %s where name='Jame';" # cur.execute(sql,[data]) # db.commit() # except Exception as e: # db.rollback() # print(e) # 獲取圖片 sql = "select image from class_1 where name='Jame'" cur.execute(sql) data = cur.fetchone() with open('girl.jpg','wb') as f: f.write(data[0]) cur.close() # 關閉遊標 db.close() # 關閉數據庫
pymysql寫操做
import pymysql # 鏈接數據庫 db = pymysql.connect(host='localhost', port=3306, user='root', password='123456', database='stu', harset='utf8') cur = db.cursor() # 獲取遊標 (操做數據庫,執行sql語句) # 寫數據庫 try: # 寫sql語句執行 # 插入操做 name = input('Name:') age = input('Age:') score = input('Score:') # 將變量插入到sql語句合成最終操做語句 sql = "insert into class_1 (name,age,score) values ('%s',%d,%f)" % (name, age, score) # 或者 # sql = "insert into class_1 (name,age,score) values (%s,%s,%s)" # 可使用列表直接給sql語句的values 傳值 cur.execute(sql,[name,age,score]) #執行 # 修改操做 sql = "update interest set price=11800 where name = 'Abby'" cur.execute(sql) sql = "delete from class_1 where score<80" # 刪除操做 cur.execute(sql) db.commit() # 提交 except Exception as e: db.rollback() # 退回到commit執行以前的數據庫狀態 print(e) cur.close() # 關閉遊標 db.close() # 關閉數據庫
字典dict.txt在github上,將詞典中的詞輸入到數據庫中的代碼
import pymysql import re f = open('dict.txt') # 打開文件 # 鏈接數據庫 db = pymysql.connect(host='localhost', port=3306, user='root', password='123456', database='dict', charset='utf8') cur = db.cursor() # 獲取遊標 (操做數據庫,執行sql語句) sql = "insert into words (word,mean) values (%s,%s)" for line in f: # 獲取單詞和解釋 tup = re.findall(r"(\S+)\s+(.*)", line)[0] # [('a', 'indef art one'), ('abandonment', 'n.abandoning')...] try: cur.execute(sql, tup) db.commit() except: db.rollback() f.close() cur.close() # 關閉遊標 db.close() # 關閉數據庫
數據庫註冊登陸程序
import pymysql # 鏈接數據庫 db = pymysql.connect(host='localhost', port=3306, user='root', password='123456', database='stu', charset='utf8') cur = db.cursor() # 獲取遊標 (操做數據庫,執行sql語句) # 註冊,判斷用戶名是否重複 def register(): name = input("用戶名:") passwd = input("密 碼:") sql = "select * from user where name='%s'" % name cur.execute(sql) result = cur.fetchone() # 獲取查詢結果集的第一條數據 if result: # 若是用戶名存在 return False try: sql = "insert into user (name, passwd) values (%s,%s)" cur.execute(sql, [name, passwd]) db.commit() return True except: db.rollback() # 回滾 return False # 登陸 def login(): name = input("用戶名:") passwd = input("密 碼:") sql = "select * from user where name='%s' and passwd='%s'" % (name, passwd) cur.execute(sql) result = cur.fetchone() # 獲取查詢結果集的第一條數據 if result: return True while True: print(""" =============== 1.註冊 2.登陸 ===============""") cmd = input("輸入命令:") if cmd == '1': # 執行註冊 if register(): print("註冊成功") else: print("註冊失敗") elif cmd == '2': # 執行登陸 if login(): print("登陸成功") break else: print("登陸失敗") else: print("我也作不到啊") cur.close() # 關閉浮標 db.close() # 關閉數據庫