?1.SQL的概述
SQL的全稱:Structured Query Language,結(jié)構(gòu)化查詢語言,用于訪問和處理數(shù)據(jù)庫的標(biāo)準(zhǔn)計(jì)算機(jī)語言。
SQL語言1974年有Boyce和Chamberlin提出的,并且首先在IBM公司研制的關(guān)系數(shù)據(jù)庫系統(tǒng)SystemR上實(shí)現(xiàn)。
經(jīng)過多年發(fā)展,SQL已經(jīng)成為數(shù)據(jù)庫領(lǐng)域同意的數(shù)據(jù)操作標(biāo)準(zhǔn)語言,可以說幾乎市面上所有的數(shù)據(jù)庫系統(tǒng)都支持使用SQL語言來操作。
SQL語言的分類:
由于數(shù)據(jù)庫管理系統(tǒng)(數(shù)據(jù)庫軟件)功能非常多,不僅僅是存儲(chǔ)數(shù)據(jù),還要包括數(shù)據(jù)的管理、表的管理、庫的管理、賬戶管理、權(quán)限管理等等。
所以基于操作數(shù)據(jù)庫的SQL語言,也基于此功能劃分為四類:
-
數(shù)據(jù)定義:DDL(Data Definition Language)
庫的創(chuàng)建刪除、表的創(chuàng)建刪除等
-
數(shù)據(jù)操控:DML(Data Manipulation Language)
新增數(shù)據(jù)、刪除數(shù)據(jù)、修改數(shù)據(jù)等
-
數(shù)據(jù)控制:DCL(Data Control Language)
新增用戶、刪除用戶、密碼修改、權(quán)限管理等
-
數(shù)據(jù)查詢:DQL(Data Query Language)
基于需求查詢和計(jì)算數(shù)據(jù)
SQL的語法特征:
在學(xué)習(xí)DDL、DQL等之前,我們先來了解SQL的語法特征。
-
SQL語言,大小寫不敏感
-
SQL可以單行或多行書寫,最后以;號(hào)結(jié)束
-
SQL支持注釋:
-
單行注釋:--注釋內(nèi)容 (-- 后面一定要有一個(gè)空格)
-
單行注釋:# 注釋內(nèi)容 (#后面可以不加空格,推薦加上)
-
多行注釋:/* 注釋內(nèi)容 */
show -- 這是第一種注釋方法 # 這是第二種注釋方法 /* 多行注釋 * */ databases;
?
?2.SQL的DDL
DDL是指數(shù)據(jù)定義語言,用來對(duì)數(shù)據(jù)庫中庫表建立刪除定義的。
創(chuàng)建庫:
# 查看數(shù)據(jù)庫 SHOW DATABASES # 使用數(shù)據(jù)庫 USE 數(shù)據(jù)庫名稱: # 創(chuàng)建數(shù)據(jù)庫 CREATE DATABASE數(shù)據(jù)庫名稱[CHARSET UTF8]: # 刪除數(shù)據(jù)庫 DROP DATABASE數(shù)據(jù)庫名稱; # 查看當(dāng)前使用的數(shù)據(jù)庫 SELECT DATABASE();
創(chuàng)建表和刪除表:
?
?
# 查看有哪些表 SHOW TABLES; # 注意要先選擇數(shù)據(jù)庫 # 創(chuàng)建表 create table 表名稱( ? 列名稱 列類型, ? 列名稱 列類型, ? …… ); ? drop table 表名稱; drop table if exists 表名稱; drop table where 條件判斷;
列類型:
-- 列類型: int -- 整數(shù) float -- 浮點(diǎn)數(shù) varchar(長(zhǎng)度) -- 文本,長(zhǎng)度為數(shù)字,做最大長(zhǎng)度限制 date -- 日期類型 timestamp -- 時(shí)間戳類型
3.SQL的DML
DML是指數(shù)據(jù)操作語言,用來對(duì)數(shù)據(jù)庫中表的數(shù)據(jù)記錄進(jìn)行更新。
關(guān)鍵字:
-
插入INSERT
-
刪除DELETE
-
更新UPDATE
基礎(chǔ)語法:
insert into 表(列1,列2,列3,列4,……,列N) values(值1,值2,值3,……,值N)[(值1,值2,值3,……,值N),……,(值1,值2,值3,……,值N)]
示例:
create table student( ? id int, ? name varchart(20), ? age int ); ? # 僅插入id數(shù)據(jù) insert into student(id) values(1000),(1002),(1003); # 插入全部id列數(shù)據(jù) insert into student(id, name, age) values(1001, '張三', 20),(1002, '李四', 19),(1003, '王五', 21); # 插入全部列數(shù)據(jù),快捷寫法 insert into student values(1001, '張三', 20),(1002, '李四', 19),(1003, '王五', 21);
數(shù)據(jù)刪除DELETE:
基礎(chǔ)語法:
DELETE FROM 表名稱 WHERE 條件判斷 條件判斷:列 操作符 值 操作符:= < > <= >= != 等 如: id = 5 id < 3 id >= 6 id != 5
演示案例:
CREATE TABLE student(
id int,
name varchar(10),
age int
);
?
INSERT INTO student(id) values(1), (2), (3);
/*
* 等價(jià)于下面的代碼
* INSERT INTO student(id) values(1);
* INSERT INTO student(id) values(2);
* INSERT INTO student(id) values(3);
*/
?
insert into student(id, name, age) values(4, '張三', 31),(5, '李四',33);
delete from student where age = 33;
4.SQL的DQL
1.基礎(chǔ)查詢
基礎(chǔ)語法:SELECT 字段列表|* FROM表
含義就是:從(FROM)表中,選擇(SELECT)某些列進(jìn)行展示
代碼演示:
select id, name from student; select * from student; select * from student where age > 20; select * from student where id = '張三';
2.分組聚合
分組聚合應(yīng)用場(chǎng)景,如:統(tǒng)計(jì)班級(jí)中男生和女生的人數(shù)。
這種需求就需要:
-
按性別分組
-
統(tǒng)計(jì)各組的人數(shù)
這就稱之為:分組聚合。
基礎(chǔ)語法:
select 字段|聚合函數(shù) from 表 [where 條件] group by 列 聚合函數(shù): sum(列) 求和 avg(列) 求平均值 min(列) 求最小值 max(列) 求最大值 count(列|*) 求數(shù)量
示例:
select gender, avg(age), sum(age), min(age), max(age), count(avg) from student group by gender;
3.排序分頁
結(jié)果排序:
可以對(duì)查詢結(jié)果,使用order by
關(guān)鍵字,指定某個(gè)列進(jìn)行排序,語法:
select 列|聚合函數(shù)|* from 表 where …… group by …… order by …… [ASC | DESC]
示例:
select * from student where age > 20 order by age asc; select * from student where age > 20 order by age desc;
結(jié)果分頁限制:
同樣,可以使用limit
關(guān)鍵字,對(duì)查詢結(jié)果進(jìn)行數(shù)量限制或分頁顯示,語法:
select 列|聚合函數(shù)|* from 表 where …… group by …… order by …… [asc | desc] limit n[, m]
示例:
select * from student limit 10; # 取10條信息 select * from student limit 10, 5; # 從第11條開始往后取5條 select * from student where age > 20 group by age order by age limit 3;
5.Python操作MySQL基礎(chǔ)使用
1.基礎(chǔ)使用
pymysql
除了使用圖像化工具以外,我們也可以使用編程編程語言來執(zhí)行SQL從而操作數(shù)據(jù)庫。
在Python中,使用第三方庫:pymysql來完成對(duì)MySQL數(shù)據(jù)庫的操作。
安裝:pip install pymysql
?
?but,一開始,在我的命令提示符里面怎么都下不下來,這時(shí)候按照notice里面的To update run后面的綠色的代碼,粘貼到下面來進(jìn)行操作:
?
?或者使用下列的方式:
pip install pymysql -i http://pypi.douban.com/simple/ --trusted-host [pypi.douban.com](http://pypi.douban.com/)
?
?創(chuàng)建到MySQL的數(shù)據(jù)庫鏈接
代碼如下:
from pymysql import Connection
# 獲取到MySQL數(shù)據(jù)庫的連接對(duì)象
conn = Connection(
? ?host='localhost', # 主機(jī)名(或者IP地址)
? ?port=3306, ?# 端口,默認(rèn)3306
? ?user='root', ?# 賬戶名
? ?password='123456' # 密碼
)
# 打開MySQL數(shù)據(jù)庫軟件信息
print(conn.get_server_info())
# 關(guān)閉到數(shù)據(jù)庫的鏈接
conn.close()
或者輸入如下的代碼:
import pymysql
?
db = pymysql.connect(
? ?host="localhost",
? ?port=3306,
? ?user='root', ? ?#在這里輸入用戶名
? ?password='qazwsxedc.2345', ? ? #在這里輸入密碼
? ?charset='utf8mb4'
? ) #連接數(shù)據(jù)庫
?
cursor = db.cursor() #創(chuàng)建游標(biāo)對(duì)象
?
sql = 'show databases' #sql語句
?
cursor.execute(sql) ?#執(zhí)行sql語句
?
one = cursor.fetchone() ?#獲取一條數(shù)據(jù)
print('one:',one)
?
many = cursor.fetchmany(3) #獲取指定條數(shù)的數(shù)據(jù),不寫默認(rèn)為1
print('many:',many)
?
all = cursor.fetchall() #獲取全部數(shù)據(jù)
print('all:',all)
?
cursor.close()
db.close() ?#關(guān)閉數(shù)據(jù)庫的連接
?
?出現(xiàn)上圖界面就說明pymysql成功將pycharm和mysql連接起來了。
執(zhí)行查詢性質(zhì)的SQL語句:
from pymysql import Connection
# 獲取到MySQL數(shù)據(jù)庫的連接對(duì)象
conn = Connection(
? ?host='localhost',
? ?port=3306,
? ?user='root',
? ?password='2345'
)
# 獲取游標(biāo)對(duì)象
cursor = conn.cursor()
conn.select_db("world")
# 使用游標(biāo)對(duì)象,執(zhí)行sql語句
cursor.execute("SELECT * FROM student")
# 獲取查詢結(jié)果
results = cursor.fetchall()
for r in results:
? ?print(r)
# 關(guān)閉到數(shù)據(jù)庫的鏈接
conn.close()
2.數(shù)據(jù)插入
commit提交
pymysql在執(zhí)行數(shù)據(jù)插入或其它產(chǎn)生數(shù)據(jù)更改的SQL語句時(shí),默認(rèn)是需要提交更改的,即,需要通過代碼“確認(rèn)”這種更改行為。
通過鏈接對(duì)象.commit()即可確認(rèn)此行為。
from pymysql import Connection
# 獲取到MySQL數(shù)據(jù)庫的連接對(duì)象
conn = Connection(
? ?host='localhost',
? ?port=3306,
? ?user='root',
? ?password='2345'
)
# 獲取游標(biāo)對(duì)象
cursor = conn.cursor()
conn.select_db("world")
# 使用游標(biāo)對(duì)象,執(zhí)行sql語句
cursor.execute("insert into student values(10001, '唐七', 19)")
# 關(guān)閉到數(shù)據(jù)庫的鏈接
conn.close()
6.綜合案例
使用SQL語句和pymysql庫完成綜合案例的開發(fā)
?
?DDL定義:
本次需求開發(fā)我們需要新建一個(gè)數(shù)據(jù)庫來使用,數(shù)據(jù)庫名稱:py_sql
基于數(shù)據(jù)結(jié)構(gòu),可以得到建表語句:
CREATE TABLE order( ? order_date DATE, ? order_id, VARCHAR(255), ? money INT, ? province VARCHAR(10) );
實(shí)現(xiàn)步驟:文章來源:http://www.zghlxwxcb.cn/news/detail-473986.html
讀取數(shù)據(jù) -> 封裝數(shù)據(jù)對(duì)象 -> 構(gòu)建數(shù)據(jù)庫鏈接 -> 寫入數(shù)據(jù)庫文章來源地址http://www.zghlxwxcb.cn/news/detail-473986.html
import ..
text_file_reader = TextFileReader("D:/2011年1月銷售數(shù)據(jù).txt")
json_file_reader = JsonFileReader("0:/2011年2月銷售數(shù)據(jù)JS0N.txt")
jan_data:list[Record] = text_file_reader.read_data()
feb_data:list[Record] = json_file_reader.read_data()
# 將2個(gè)月份的數(shù)據(jù)合并list來存儲(chǔ)
all_data:list[Record] = jan_data + feb_data
# 構(gòu)建MySQL鏈接對(duì)象
cursor = conn.cursor()
conn.select_db("py_sql")
# 組織SQL語句
for record in all_data:
sql = f"insert into orders(order_data, order_id, money, province)"
f"values('{record.date}','{record.order_id)'{record.noney},'{record.province}')"
print(sql)
cursor.excute(sql)
conn.close()
到了這里,關(guān)于一篇文章打好SQL基礎(chǔ),熟悉數(shù)據(jù)庫的基礎(chǔ)操作和方法,以及安裝MySQL軟件包和Python操作MySQL基礎(chǔ)使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!