6:MySQL與Python交互

總體內(nèi)容

1.1、SQL語句的強化

1.2、python安裝pymysql

1.3、參數(shù)化(sql防注入)

一、SQL語句的強化

1.1、創(chuàng)建數(shù)據(jù)庫(jing_dong)、數(shù)據(jù)表(goods)、插入數(shù)據(jù)

create database jing_dong charset=utf8;

使用 "京東" 數(shù)據(jù)庫

use jing_dong;

創(chuàng)建一個商品goods數(shù)據(jù)表

提示:

id:主鍵

name:商品的名字

cate_name: 商品的類型

brand_name:商品的品牌

price:商品的價格

is_show:是否顯示商品

is_saleoff:商品是否賣完

插入數(shù)據(jù),向goods表中插入數(shù)據(jù)

insert into goods values(0,'r510vc 15.6英寸筆記本','筆記本','華碩','3399',default,default);

insert into goods values(0,'y400n 14.0英寸筆記本電腦','筆記本','聯(lián)想','4999',default,default);

insert into goods values(0,'g150th 15.6英寸游戲本','游戲本','雷神','8499',default,default);

insert into goods values(0,'x550cc 15.6英寸筆記本','筆記本','華碩','2799',default,default);

insert into goods values(0,'x240 超極本','超級本','聯(lián)想','4880',default,default);

insert into goods values(0,'u330p 13.3英寸超極本','超級本','聯(lián)想','4299',default,default);

insert into goods values(0,'svp13226scb 觸控超極本','超級本','索尼','7999',default,default);

insert into goods values(0,'ipad mini 7.9英寸平板電腦','平板電腦','蘋果','1998',default,default);

insert into goods values(0,'ipad air 9.7英寸平板電腦','平板電腦','蘋果','3388',default,default);

insert into goods values(0,'ipad mini 配備 retina 顯示屏','平板電腦','蘋果','2788',default,default);

insert into goods values(0,'ideacentre c340 20英寸一體電腦 ','臺式機','聯(lián)想','3499',default,default);

insert into goods values(0,'vostro 3800-r1206 臺式電腦','臺式機','戴爾','2899',default,default);

insert into goods values(0,'imac me086ch/a 21.5英寸一體電腦','臺式機','蘋果','9188',default,default);

insert into goods values(0,'at7-7414lp 臺式電腦 linux )','臺式機','宏碁','3699',default,default);

insert into goods values(0,'z220sff f4f06pa工作站','服務(wù)器/工作站','惠普','4288',default,default);

insert into goods values(0,'poweredge ii服務(wù)器','服務(wù)器/工作站','戴爾','5388',default,default);

insert into goods values(0,'mac pro專業(yè)級臺式電腦','服務(wù)器/工作站','蘋果','28888',default,default);

insert into goods values(0,'hmz-t3w 頭戴顯示設(shè)備','筆記本配件','索尼','6999',default,default);

insert into goods values(0,'商務(wù)雙肩背包','筆記本配件','索尼','99',default,default);

insert into goods values(0,'x3250 m4機架式服務(wù)器','服務(wù)器/工作站','ibm','6888',default,default);

insert into goods values(0,'商務(wù)雙肩背包','筆記本配件','索尼','99',default,default);

1.2、SQL語句的強化練習(xí)

(1)、查詢類型cate_name為 '超級本' 的商品名稱、價格

selectname,pricefromgoodswherecate_name="超級本";

(2)、顯示商品的種類

// 僅僅顯示商品的種類,簡單快速

select distinct cate_name from goods;

// 顯示商品的種類,功能更強大,需要的時間比上面的 distinct 去重時間長

select cate_name from goods group by cate_name;

(3)、求所有電腦產(chǎn)品的平均價格,并且保留兩位小數(shù)

select round(avg(price),2) from goods;

(4)、顯示每種商品的平均價格

select cate_name,round(avg(price),2) from goods group by cate_name;

(5)、查詢每種類型的商品中 最貴、最便宜、平均價、數(shù)量

select cate_name,max(price),min(price),avg(price),count(*) from goods group by cate_name;

(6)、查詢所有價格大于平均價格的商品,并且按價格降序排序

selectid,name,pricefromgoodswhereprice>(selectround(avg(price),2)asavg_pricefromgoods)order by price desc;

(7)、查詢每種類型中最貴的電腦信息

select * from goods

inner join

? ? (

? ? ? ? select

? ? ? ? cate_name,

? ? ? ? max(price) as max_price,

? ? ? ? min(price) as min_price,

? ? ? ? avg(price) as avg_price,

? ? ? ? count(*) from goods group by cate_name

? ? ) as goods_new_info

on goods.cate_name=goods_new_info.cate_name and goods.price=goods_new_info.max_price;

1.3、創(chuàng)建 "商品分類"" 表 (也就是把上面的goods表拆為多個表),目標(biāo)把 cate_name 與 brand_name 拆為單獨的 good_cates 與 good_brands 兩個表,最后把 goods 里面的cate_name 與 brand_name 改為 cate_id 與 brand_id ,類型改為 int unsigned,也就是與新表的主鍵id類型保持一致

create table if not exists good_cates(

? ? ? ? id int unsigned primary key auto_increment,

? ? ? ? name varchar(40) not null

);

查詢goods表中商品的種類

selectcate_namefromgoodsgroupby cate_name;

將上面分組結(jié)果寫入到goods_cates數(shù)據(jù)表

insert into good_cates (name) select cate_name from goods group by cate_name;

提示:insert into good_cates (name)后面不需要再加 values .....,查出來的數(shù)據(jù)直接寫入即可

1.4、同步表數(shù)據(jù)

通過 goods_cates 數(shù)據(jù)表來更新goods表的 cate_name,也就是cate_name的數(shù)據(jù)用表goods_cates里面的id替換

update goods as g inner join good_cates as c on g.cate_name=c.name set g.cate_name=c.id;

1.5、修改表結(jié)構(gòu)

查看 goods 的數(shù)據(jù)表結(jié)構(gòu),會發(fā)現(xiàn) cate_name 對應(yīng)的類型為 varchar 但是存儲的都是數(shù)字,要更改其類型

通過 alter table語句 修改表結(jié)構(gòu),也就是修改 cate_name 的類型為 int unsigned,并把名字改為 cate_id

alter table goods change cate_name cate_id int unsigned not null;

提示: change 與 modify 區(qū)別:

change : 修改表-修改字段:重命名版(字段名字、類型、及約束 都可以改變),如:alter table 表名 change 原名 新名 類型及約束;

modify: 修改表-修改字段:不重命名版(字段名字不變,類型以及約束可以改變),如:alter table 表名 modify 列名 類型及約束;

1.6、外鍵

在 goods_cates 表中插入記錄

insert into goods_cates(name) values ('路由器'),('交換機'),('網(wǎng)卡');?

在 goods 數(shù)據(jù)表中寫入任意記錄

insert into goods (name,cate_id,brand_name,price) values('LaserJet Pro P1606dn 黑白激光打印機', 12, '華碩','1849');

查詢所有商品的詳細(xì)信息 (通過內(nèi)連接)

select g.id,g.name,c.name,g.price from goods as g inner join good_cates as c on g.cate_id=c.id;

如何防止無效信息的插入,就是可以在插入前判斷類型或者品牌名稱是否存在呢? 可以使用之前講過的外鍵來解決

外鍵約束:對數(shù)據(jù)的有效性進行驗證

關(guān)鍵字: foreign key,只有 innodb數(shù)據(jù)庫引擎 支持外鍵約束

對于已經(jīng)存在的數(shù)據(jù)表 如何更新外鍵約束

讓 cate_id 成為外鍵

把 goods商品里面的最后一條數(shù)據(jù)刪掉,不然后面后面外鍵的設(shè)置會失敗

delete from goods whereid=22;

設(shè)置 cate_id 成為外鍵

alter table goodsaddforeign key(cate_id)referencesgood_cates(id);

這個時候我們?nèi)绻诓迦胪?goods里面插入一條包含 cate_id = 12 的就會報錯了,因為 12 在 good_cates 表里找不到

1.7、如何在創(chuàng)建數(shù)據(jù)表的時候就設(shè)置?外鍵約束?呢?,注意: goods 中的 cate_id 的類型一定要和 goods_cates 表中的 id 類型一致

創(chuàng)表,設(shè)置外鍵

如何取消外鍵約束

需要先獲取外鍵約束名稱,該名稱系統(tǒng)會自動生成,可以通過查看表創(chuàng)建語句來獲取名稱

show create table goods;

獲取名稱之后就可以根據(jù)名稱來刪除外鍵約束

alter table goods drop foreign key 外鍵名稱;

提示: 在實際開發(fā)中,很少會使用到外鍵約束,會極大的降低表更新的效率

1.8、上面我們已經(jīng)完成了 表 good_cates 的操作,下面我們來快速的創(chuàng)建一下 good_brands 表

(1)、通過create...select來創(chuàng)建數(shù)據(jù)表并且同時寫入記錄,一步到位

在創(chuàng)建數(shù)據(jù)表的時候一起插入數(shù)據(jù)

(2)、同步數(shù)據(jù)

通過goods_brands數(shù)據(jù)表來更新goods數(shù)據(jù)表

update goods as g inner join good_brands as b on g.brand_name=b.name set g.brand_name=b.id;

(3)、修改表結(jié)構(gòu)

查看 goods 的數(shù)據(jù)表結(jié)構(gòu),會發(fā)現(xiàn) cate_name 和 brand_name對應(yīng)的類型為 varchar 但是存儲的都是數(shù)字

通過alter table語句修改表結(jié)構(gòu)(下面是可以同事修改另兩個字段的,cate_name我們已經(jīng)修改過)

alter table goods change cate_name cate_id int unsigned not null,change brand_name brand_id int unsigned not null;

alter table goods change brand_name brand_id int unsigned not null;

(4)、brand_id 設(shè)置為 goods表的 外鍵

alter table goods add foreign key (brand_id) references good_brands(id);

5)、取消外鍵約束

需要先獲取外鍵約束名稱,該名稱系統(tǒng)會自動生成,可以通過查看表創(chuàng)建語句來獲取名稱

show create table goods;

獲取名稱之后就可以根據(jù)名稱來刪除外鍵約束

alter table goods drop foreign key 外鍵名稱;

二、python安裝pymysql 與 Python 操作

2.1、在終端安裝pymysql:?pip3 install pymysql

2.2、Python 中操作 MySQL 步驟

(1)、引入模塊:在py文件中引入pymysql模塊

from pymysql import *

(2)、Connection 對象

用于建立與數(shù)據(jù)庫的連接

創(chuàng)建對象:調(diào)用connect()方法

conn=connect(參數(shù)列表)

例如:

conn = connect(host='域名或者IP',port=3306,database='數(shù)據(jù)庫名',user='用戶名',password='密碼',charset='utf8')

參數(shù)host:連接的mysql主機,如果本機是'localhost',服務(wù)器的話就是:域名或者IP

參數(shù)port:連接的mysql主機的端口,默認(rèn)是3306

參數(shù)database:數(shù)據(jù)庫的名稱

參數(shù)user:連接的用戶名

參數(shù)password:連接的密碼

參數(shù)charset:通信采用的編碼方式,推薦使用utf8

3)、對象的方法

close()關(guān)閉連接

commit()提交

cursor()返回Cursor(游標(biāo))對象,用于執(zhí)行sql語句并獲得結(jié)果

(4)、Cursor對象

用于執(zhí)行sql語句,使用頻度最高的語句為select、insert、update、delete

獲取Cursor對象:調(diào)用Connection對象的cursor()方法

cs1=conn.cursor()

(5)、對象的方法

close()關(guān)閉

execute(operation [, parameters ])執(zhí)行語句,返回受影響的行數(shù),主要用于執(zhí)行insert、update、delete語句,也可以執(zhí)行create、alter、drop等語句

count = cs1.execute('select * from goods') # 返回是表中數(shù)據(jù)的個數(shù)

fetchone()執(zhí)行查詢語句時,獲取查詢結(jié)果集的第一個行數(shù)據(jù),返回一個元組

fetchall()執(zhí)行查詢時,獲取結(jié)果集的所有行,一行構(gòu)成一個元組,再將這些元組裝入一個元組返回

fetchmany(數(shù)量)執(zhí)行查詢時,獲取結(jié)果集的所有行,一行構(gòu)成一個元組,再將這些元組裝入一個元組返回,也就是元組套元組

(6)、對象的屬性

rowcount只讀屬性,表示最近一次execute()執(zhí)行后受影響的行數(shù)

connection獲得當(dāng)前連接對象

2.3、python操作sql:查、增、改、刪?數(shù)據(jù)

共用代碼

from pymysql import *

def main():

? ? # 創(chuàng)建Connection連接

? ? conn = connect(host='ironman.ren',port=3306,database='jing_dong',user='root',password='456123love',charset='utf8')

? ? # 獲得Cursor(游標(biāo))對象

? ? cursor = conn.cursor()

? ? """"增刪改查的代碼"""

? ? # 關(guān)閉Cursor對象

? ? cursor.close()

? ? # 關(guān)閉Connection對象

? ? conn.close()

(1)、查詢數(shù)據(jù)

查詢數(shù)據(jù)庫某個表的全部數(shù)據(jù)個數(shù)

count = cursor.execute('select * from goods')

print("總數(shù)量count=%d"%count)

打印結(jié)果:21

查詢數(shù)表goods里面所有的信息:fetchall()

cursor.execute('select * from goods')

print(cursor.fetchall())

查詢數(shù)表goods里面部分的信息:fetchmany(數(shù)量)

print(cursor.fetchmany(3))

查詢數(shù)表goods里面一條信息:fetchone()

print(cursor.fetchone())

2)、增加數(shù)據(jù):執(zhí)行insert語句,并返回受影響的行數(shù):添加一條數(shù)據(jù)

count = cursor.execute('insert into goods values(0,"笨蛋 超極本",5,4,4000,0,0)')

# 提交之前的操作,如果之前已經(jīng)之執(zhí)行過多次的execute,那么就都進行提交

3)、改:更新數(shù)據(jù)

count = cursor.execute('update goods set name = "超級笨蛋 超極本" where name = "笨蛋 超極本" ')

conn.commit()

(4)、刪:數(shù)據(jù)

count = cursor.execute('delete from goods where name="超級笨蛋 超極本" ')

conn.commit()

提示: 除了查詢外,增、改、刪 都需要 conn.commit()

conn.commit(): 提交之前的操作,如果之前已經(jīng)之執(zhí)行過多次的execute,那么就都進行提交

.4、python操作goods表:所有數(shù)據(jù)、品牌分類、所有的分類

from pymysql import *

class JD(object):

? ? def __init__(self):

? ? ? ? # 1、創(chuàng)建連接

? ? ? ? self.connection = connect(host='ironman.ren', port=3306, database='jing_dong', user='root', password='456123love',

? ? ? ? ? ? ? ? ? ? ? charset='utf8')

? ? ? ? # 2、獲取cursor(游標(biāo))對象

? ? ? ? self.cursor = self.connection.cursor()

? ? def __del__(self):

? ? ? ? # 5、關(guān)閉游標(biāo)

? ? ? ? self.cursor.close()

? ? ? ? # 6、關(guān)閉數(shù)據(jù)庫連接

? ? ? ? self.connection.close()

? ? @staticmethod

? ? def print_munu():

? ? ? ? print("京東商品查詢")

? ? ? ? print("1.所有商品")

? ? ? ? print("2.所有商品分類")

? ? ? ? print("3.所有商品品牌分類")

? ? ? ? return input("請輸入功能對應(yīng)的序號:")

? ? def execute_sql(self,sql):

? ? ? ? ? count = self.cursor.execute(sql)

? ? ? ? ? print(count)

? ? ? ? ? """ 所有數(shù)據(jù)、品牌分類、所有的分類 """

? ? ? ? ? for item in self.cursor.fetchall():

? ? ? ? ? ? ? ? print(item)

? ? def select_run(self):

? ? ? ? while True:

? ? ? ? ? ? num = self.print_munu()

? ? ? ? ? ? if num == "1":

? ? ? ? ? ? ? ? ? # 所有商品

? ? ? ? ? ? ? ? ? self.show_all_items()

? ? ? ? ? ? elif num == "2":

? ? ? ? ? ? ? ? ? # 所有商品分類

? ? ? ? ? ? ? ? ? self.show_all_cates()

? ? ? ? ? ? elif num == "3":

? ? ? ? ? ? ? ? ? # 所有商品品牌分類

? ? ? ? ? ? ? ? ? self.show_all_brand()

? ? def show_all_items(self):

? ? ? ? # 3、使用游標(biāo)對象

? ? ? ? # 3.1、查詢這個good表

? ? ? ? sql = 'select * from goods'

? ? ? ? self.execute_sql(sql)

? ? def show_all_brand(self):

? ? ? ? # 3.2、查詢這個good表

? ? ? ? sql = 'select * from good_brands'

? ? ? ? self.execute_sql(sql)

? ? def show_all_cates(self):

? ? ? ? # 3.3、查詢這個good表

? ? ? ? sql = 'select * from good_cates'

? ? ? ? self.execute_sql(sql)

def main():

? ? ? # 1、創(chuàng)建京東對象

? ? ? jd = JD()

? ? ? # 2、調(diào)用查詢

? ? ? jd.select_run()

if __name__ == "__main__":

? ? ? main()

三、參數(shù)化(sql防注入)

3.1、我們來看一個用戶搜索商品的例子,根據(jù)用戶輸入的信息進行查詢

from pymysql import *

class JD(object):

? ? def __init__(self):

? ? ? ? # 1、創(chuàng)建連接

? ? ? ? self.connection = connect(host='ironman.ren', port=3306, database='jing_dong', user='root',

? ? ? ? ? ? ? ? ? ? ? ? ? ? password='456123love',

? ? ? ? ? ? ? ? ? ? ? ? ? ? charset='utf8')

? ? ? ? # 2、獲取cursor(游標(biāo))對象

? ? ? ? self.cursor = self.connection.cursor()

? ? def __del__(self):

? ? ? ? # 5、關(guān)閉游標(biāo)

? ? ? ? self.cursor.close()

? ? ? ? # 6、關(guān)閉數(shù)據(jù)庫連接

? ? ? ? self.connection.close()

? ? def select_commodity(self):


? ? ? ? while True:


? ? ? ? ? ? select_content = input("請輸入搜索的商品內(nèi)容:")

? ? ? ? ? ? params = [select_content]

? ? ? ? ? ? self.cursor.execute("select * from goods where name = %s",params)

? ? ? ? ? ? for item in self.cursor.fetchall():

? ? ? ? ? ? ? ? print(item)

def main():

? ? jd = JD()

? ? jd.select_commodity()

if __name__ == "__main__":

? ? main()

3.2、提一下 3.1中的 def select_commodity(self):方法里面的sql拼接的問題,上面用的安全方式

安全方式:把搜索的內(nèi)容放到數(shù)組里面,在execute()里面,如果要是有多個參數(shù),需要進行參數(shù)化,那么params = [數(shù)值1, 數(shù)值2....],此時sql語句中有多個%s即可 ,sql語句會自動完成,不需要我們來做

select_content = input("請輸入搜索的商品內(nèi)容:")

# 構(gòu)造參數(shù)列表

params = [select_content]

self.cursor.execute("select * from goods where name = %s",params)

不安全方式:如果用戶輸入:' ' or 7=7,就會查出你數(shù)據(jù)庫所有的數(shù)據(jù),假如用戶使用的刪除操作,很可能把這個表給你全刪了??,sql注入防不勝防

select_content = input("請輸入搜索的商品內(nèi)容:")

sql = "select * from goods where name = %s"% select_content

self.cursor.execute(sql)

提示:sql語句的參數(shù)化,可以有效防止sql注入


作者:IIronMan

鏈接:http://www.itdecent.cn/p/c4a65e1b3d84

來源:簡書

著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容