乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      MySQL與Python

       寧?kù)o致遠(yuǎn)oj1kn5 2019-05-12

      一. 準(zhǔn)備數(shù)據(jù)

      -- 創(chuàng)建 "京東" 數(shù)據(jù)庫(kù)
      create database jing_dong charset=utf8;
      
      -- 使用 "京東" 數(shù)據(jù)庫(kù)
      use jing_dong;
      
      -- 創(chuàng)建一個(gè)商品goods數(shù)據(jù)表
      create table goods(
          id int unsigned primary key auto_increment not null,
          name varchar(150) not null,
          cate_name varchar(40) not null,
          brand_name varchar(40) not null,
          price decimal(10,3) not null default 0,
          is_show bit not null default 1,
          is_saleoff bit not null default 0
      );
      
      -- 向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 超極本','超級(jí)本','聯(lián)想','4880',default,default); 
      insert into goods values(0,'u330p 13.3英寸超極本','超級(jí)本','聯(lián)想','4299',default,default); 
      insert into goods values(0,'svp13226scb 觸控超極本','超級(jí)本','索尼','7999',default,default); 
      insert into goods values(0,'ipad mini 7.9英寸平板電腦','平板電腦','蘋(píng)果','1998',default,default);
      insert into goods values(0,'ipad air 9.7英寸平板電腦','平板電腦','蘋(píng)果','3388',default,default); 
      insert into goods values(0,'ipad mini 配備 retina 顯示屏','平板電腦','蘋(píng)果','2788',default,default); 
      insert into goods values(0,'ideacentre c340 20英寸一體電腦 ','臺(tái)式機(jī)','聯(lián)想','3499',default,default); 
      insert into goods values(0,'vostro 3800-r1206 臺(tái)式電腦','臺(tái)式機(jī)','戴爾','2899',default,default); 
      insert into goods values(0,'imac me086ch/a 21.5英寸一體電腦','臺(tái)式機(jī)','蘋(píng)果','9188',default,default); 
      insert into goods values(0,'at7-7414lp 臺(tái)式電腦 linux )','臺(tái)式機(jī)','宏碁','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專(zhuān)業(yè)級(jí)臺(tái)式電腦','服務(wù)器/工作站','蘋(píng)果','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機(jī)架式服務(wù)器','服務(wù)器/工作站','ibm','6888',default,default); 
      insert into goods values(0,'商務(wù)雙肩背包','筆記本配件','索尼','99',default,default);
      

      二. SQL演練

      1. 基本查詢(xún)

      -- 查詢(xún)商品類(lèi)型為超極本的所有記錄
       select * from goods whoods where cate_name="超級(jí)本";
       
      -- 顯示商品種類(lèi)
      select distinct cate_name from goods; 
      select cate_name from goods group by cate_name; -- 功能更強(qiáng)
      
      -- 求所有電腦產(chǎn)品的平均價(jià)格,并且保留兩位小數(shù)
      select round(avg(price),2) as avg_price from goods;
      
      -- 顯示每種商品的平均價(jià)格
      select cate_name,avg(price) as avg_price from goods group by cate_name;
      
      -- 查詢(xún)每種類(lèi)型的商品中 最貴、最便宜、平均價(jià)、數(shù)量
      select cate_name,max(price),min(price),avg(price),count(*) from goods group by cate_name;
      
      -- 查詢(xún)所有價(jià)格大于平均價(jià)格的商品,并且按價(jià)格降序排序
      select * from goods where price>(select avg(price) from goods) order by price desc;
      
      -- 查詢(xún)每種類(lèi)型中最貴的電腦信息
      select * from goods inner join (
      	select cate_name, max(price) as max_price
      	from goods 
      	group by cate_name
      ) as goods_new  -- 子查詢(xún)到的結(jié)果也可以作為一張表
      on goods.cate_name=goods_new.cate_name and goods.price=goods_new.max_price;
      

      2. 創(chuàng)建"商品分類(lèi)"表(拆表)

      -- 創(chuàng)建商品分類(lèi)表
      create table if not exists goods_cates(
          id int unsigned primary key auto_increment,
          name varchar(40) not null
      );
      
      -- 查詢(xún)goods表中商品的種類(lèi)
      select cate_name from goods group by cate_name;
      
      -- 將分組結(jié)果寫(xiě)入到goods_cates數(shù)據(jù)表
      insert into goods_cates (name) select cate_name from goods group by cate_name;
      

      3. 同步分類(lèi)表數(shù)據(jù)

      -- 通過(guò)goods_cates數(shù)據(jù)表來(lái)更新goods表
      update goods as g inner join goods_cates as c on g.cate_name=c.name set g.cate_name=c.id;
      

      4. 創(chuàng)建"商品品牌"表

      -- 通過(guò)create...select來(lái)創(chuàng)建數(shù)據(jù)表并且同時(shí)寫(xiě)入記錄,一步到位
      
      -- 取出商品品牌
      select brand_name from goods group by brand_name;
      
      -- 在創(chuàng)建數(shù)據(jù)表的時(shí)候一起插入數(shù)據(jù)
      -- 注意: 需要對(duì)brand_name 用as起別名,否則name字段就沒(méi)有值
      create table goods_brands (
          id int unsigned primary key auto_increment,
          name varchar(40) not null) select brand_name as name from goods group by brand_name;
      

      5. 同步品牌表數(shù)據(jù)

      -- 通過(guò)goods_brands數(shù)據(jù)表來(lái)更新goods表
      update goods as g inner join goods_brands as g_b on g.brand_name=g_b.name set g.brand_name=g_b.id;
      

      6. 修改表結(jié)構(gòu)

      -- 查看 goods 的數(shù)據(jù)表結(jié)構(gòu),會(huì)發(fā)現(xiàn) cate_name 和 brand_name對(duì)應(yīng)的類(lèi)型為 varchar 但是存儲(chǔ)的都是數(shù)字
      desc goods;
      
      -- 通過(guò)alter table語(yǔ)句修改表結(jié)構(gòu),改名為id,數(shù)據(jù)類(lèi)型為int unsigned
      alter table goods  
      change cate_name cate_id int unsigned not null,
      change brand_name brand_id int unsigned not null;
      

      7. 外鍵

      -- 查詢(xún)所有商品信息
      select * from goods as g 
      inner join goods_cates as c on g.cate_id
      -- 如何防止無(wú)效信息的插入,就是可以在插入前判斷類(lèi)型或者品牌名稱(chēng)是否存在呢? 可以使用之前講過(guò)的外鍵來(lái)解決
      
      -- 外鍵約束:對(duì)數(shù)據(jù)的有效性進(jìn)行驗(yàn)證
      -- 關(guān)鍵字: foreign key,只有 innodb數(shù)據(jù)庫(kù)引擎 支持外鍵約束
      -- 對(duì)于已經(jīng)存在的數(shù)據(jù)表 如何更新外鍵約束
      -- 給brand_id 添加外鍵約束
      alter table goods add foreign key (brand_id) references goods_brands(id);
      -- 給cate_id 添加外鍵約束
      alter table goods add foreign key (cate_id) references goods_cates(id);
      
      -- 已經(jīng)不能插入無(wú)效數(shù)據(jù)
      insert into goods (name,cate_id,brand_id,price)
      values('LaserJet Pro P1606dn 黑白激光打印機(jī)', 12, 4,'1849');
      
      -- 如何刪除外鍵
      
      -- 需要先獲取外鍵約束名稱(chēng),該名稱(chēng)系統(tǒng)會(huì)自動(dòng)生成,可以通過(guò)查看表創(chuàng)建語(yǔ)句來(lái)獲取名稱(chēng)(該名稱(chēng)跟在CONSTRAINT字段之后)
      show create table goods;
      -- 獲取名稱(chēng)之后就可以根據(jù)名稱(chēng)來(lái)刪除外鍵約束
      alter table goods drop foreign key 外鍵名稱(chēng);
      

      在實(shí)際開(kāi)發(fā)中,很少會(huì)使用到外鍵約束,會(huì)極大的降低表更新的效率

      三. Python操作MySQL

      1. 操作流程

      在這里插入圖片描述

      2. 引入模塊

      # python2中為: import MySQLdb
      import pymysql
      

      3. 查詢(xún)數(shù)據(jù)

      from pymysql import *
      
      def main():
          # 創(chuàng)建Connection連接
          conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
          # 獲得Cursor對(duì)象
          cs1 = conn.cursor()
          # 執(zhí)行select語(yǔ)句,并返回受影響的行數(shù):查詢(xún)一條數(shù)據(jù)
          count = cs1.execute('select id,name from goods where id>=4')
          # 打印受影響的行數(shù)
          print("查詢(xún)到%d條數(shù)據(jù):" % count)
      
          for i in range(count):
              # 獲取查詢(xún)的結(jié)果
              result = cs1.fetchone()
              # 打印查詢(xún)的結(jié)果
              print(result)
              # 獲取查詢(xún)的結(jié)果
      
          # 關(guān)閉Cursor對(duì)象
          cs1.close()
          conn.close()
      
      if __name__ == '__main__':
          main()
      

      – 除了fetchone()外, 還包括fetchmany(x)和fetchall()
      – 其中fetchmany中的x表示要取出多少行

      3. 增刪改數(shù)據(jù)

      from pymysql import *
      
      def main():
          # 創(chuàng)建Connection連接
          conn = connect(host='localhost',port=3306,database='jing_dong',user='root',password='mysql',charset='utf8')
          # 獲得Cursor對(duì)象
          cs1 = conn.cursor()
          # 執(zhí)行insert語(yǔ)句,并返回受影響的行數(shù):添加一條數(shù)據(jù)
          # 增加
          count = cs1.execute('insert into goods_cates(name) values("硬盤(pán)")')
          #打印受影響的行數(shù)
          print(count)
      	# 用三個(gè)雙引號(hào),可以避免引號(hào)中還嵌套引號(hào)的問(wèn)題
          count = cs1.execute('insert into goods_cates(name) values("光盤(pán)")')
          print(count)
      
          # # 更新
          # count = cs1.execute('update goods_cates set name="機(jī)械硬盤(pán)" where name="硬盤(pán)"')
          # # 刪除
          # count = cs1.execute('delete from goods_cates where id=6')
      
          # 提交之前的操作,如果之前已經(jīng)之執(zhí)行過(guò)多次的execute,那么就都進(jìn)行提交
          conn.commit()
      
          # 關(guān)閉Cursor對(duì)象
          cs1.close()
          # 關(guān)閉Connection對(duì)象
          conn.close()
      
      if __name__ == '__main__':
          main()
      

      – 如果不想commit(), 可以使用rollback(),清除之前執(zhí)行過(guò)多次的execute()

      4. 防止SQL注入

      – SQL注入是說(shuō),用戶(hù)把代碼輸入到字符中,使得執(zhí)行了其他功能的SQL語(yǔ)句,容易導(dǎo)致數(shù)據(jù)泄露
      – SQL語(yǔ)句的參數(shù)化,可以有效防止sql注入
      – 注意:此處不同于python的字符串格式化,全部使用%s占位

      from pymysql import *
      
      def main():
      
          find_name = input("請(qǐng)輸入物品名稱(chēng):")
      
          # 創(chuàng)建Connection連接
          conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
          # 獲得Cursor對(duì)象
          cs1 = conn.cursor()
      
      
          # # 非安全的方式
          # # 輸入 " or 1=1 or "   (雙引號(hào)也要輸入)
          # sql = 'select * from goods where name="%s"' % find_name
          # print("""sql===>%s<====""" % sql)
          # # 執(zhí)行select語(yǔ)句,并返回受影響的行數(shù):查詢(xún)所有數(shù)據(jù)
          # count = cs1.execute(sql)
      
          # 安全的方式
          # 構(gòu)造參數(shù)列表
          params = [find_name]
          # 執(zhí)行select語(yǔ)句,并返回受影響的行數(shù):查詢(xún)所有數(shù)據(jù)
          count = cs1.execute('select * from goods where name=%s', params)
          # 注意:
          # 如果要是有多個(gè)參數(shù),需要進(jìn)行參數(shù)化
          # 那么params = [數(shù)值1, 數(shù)值2....],此時(shí)sql語(yǔ)句中有多個(gè)%s即可 
      
          # 打印受影響的行數(shù)
          print(count)
          # 獲取查詢(xún)的結(jié)果
          # result = cs1.fetchone()
          result = cs1.fetchall()
          # 打印查詢(xún)的結(jié)果
          print(result)
          # 關(guān)閉Cursor對(duì)象
          cs1.close()
          # 關(guān)閉Connection對(duì)象
          conn.close()
      
      if __name__ == '__main__':
          main()
      

        本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶(hù)發(fā)布,不代表本站觀(guān)點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買(mǎi)等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評(píng)論

        發(fā)表

        請(qǐng)遵守用戶(hù) 評(píng)論公約

        類(lèi)似文章 更多