最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

MySQL和Python交互的示例

 更新時間:2021年03月08日 10:58:48   作者:Gaowaly  
這篇文章主要介紹了MySQL和Python交互的示例,幫助大家更好的理解和學習使用python,感興趣的朋友可以了解下

一.準備數(shù)據(jù)

創(chuàng)建數(shù)據(jù)表

-- 創(chuàng)建 "京東" 數(shù)據(jù)庫
create database jing_dong charset=utf8;

-- 使用 "京東" 數(shù)據(jù)庫
use jing_dong;

-- 創(chuàng)建一個商品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
);

插入數(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工作站','服務器/工作站','惠普','4288',default,default); 
insert into goods values(0,'poweredge ii服務器','服務器/工作站','戴爾','5388',default,default); 
insert into goods values(0,'mac pro專業(yè)級臺式電腦','服務器/工作站','蘋果','28888',default,default); 
insert into goods values(0,'hmz-t3w 頭戴顯示設備','筆記本配件','索尼','6999',default,default); 
insert into goods values(0,'商務雙肩背包','筆記本配件','索尼','99',default,default); 
insert into goods values(0,'x3250 m4機架式服務器','服務器/工作站','ibm','6888',default,default); 
insert into goods values(0,'商務雙肩背包','筆記本配件','索尼','99',default,default);

二.SQL演練

1. SQL語句的強化

查詢類型cate_name為 '超極本' 的商品名稱、價格

select name,price from goods where cate_name = '超級本';

顯示商品的種類

select cate_name from goods group by cate_name;

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

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

顯示每種商品的平均價格

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

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

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

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

select id,name,price from goods 
where price > (select round(avg(price),2) as avg_price from goods) 
order by price desc;

查詢每種類型中最貴的電腦信息

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;

2. 創(chuàng)建 "商品分類"" 表

-- 創(chuàng)建商品分類表
create table if not exists goods_cates(
 id int unsigned primary key auto_increment,
 name varchar(40) not null
);

查詢goods表中商品的種類

select cate_name from goods group by cate_name;

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

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

3. 同步表數(shù)據(jù)

通過goods_cates數(shù)據(jù)表來更新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)建 "商品品牌表" 表

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

-- select brand_name from goods group by brand_name;

-- 在創(chuàng)建數(shù)據(jù)表的時候一起插入數(shù)據(jù)
-- 注意: 需要對brand_name 用as起別名,否則name字段就沒有值
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ù)

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

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

6. 修改表結構

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

desc goods;

通過alter table語句修改表結構

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

7. 外鍵

分別在 goods_cates 和 goods_brands表中插入記錄

insert into goods_cates(name) values ('路由器'),('交換機'),('網(wǎng)卡');
insert into goods_brands(name) values ('海爾'),('清華同方'),('神舟');

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

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

查詢所有商品的詳細信息 (通過內連接)

select g.id,g.name,c.name,b.name,g.price from goods as g
inner join goods_cates as c on g.cate_id=c.id
inner join goods_brands as b on g.brand_id=b.id;

查詢所有商品的詳細信息 (通過左連接)

select g.id,g.name,c.name,b.name,g.price from goods as g
left join goods_cates as c on g.cate_id=c.id
left join goods_brands as b on g.brand_id=b.id;
  • 如何防止無效信息的插入,就是可以在插入前判斷類型或者品牌名稱是否存在呢? 可以使用之前講過的外鍵來解決
  • 外鍵約束:對數(shù)據(jù)的有效性進行驗證
  • 關鍵字: foreign key,只有 innodb數(shù)據(jù)庫引擎 支持外鍵約束
  • 對于已經(jīng)存在的數(shù)據(jù)表 如何更新外鍵約束
-- 給brand_id 添加外鍵約束成功
alter table goods add foreign key (brand_id) references goods_brands(id);
-- 給cate_id 添加外鍵失敗
-- 會出現(xiàn)1452錯誤
-- 錯誤原因:已經(jīng)添加了一個不存在的cate_id值12,因此需要先刪除
alter table goods add foreign key (cate_id) references goods_cates(id);
  • 如何在創(chuàng)建數(shù)據(jù)表的時候就設置外鍵約束呢?
  • 注意: goods 中的 cate_id 的類型一定要和 goods_cates 表中的 id 類型一致
create table goods(
 id int primary key auto_increment not null,
 name varchar(40) default '',
 price decimal(5,2),
 cate_id int unsigned,
 brand_id int unsigned,
 is_show bit default 1,
 is_saleoff bit default 0,
 foreign key(cate_id) references goods_cates(id),
 foreign key(brand_id) references goods_brands(id)
);

如何取消外鍵約束

-- 需要先獲取外鍵約束名稱,該名稱系統(tǒng)會自動生成,可以通過查看表創(chuàng)建語句來獲取名稱
show create table goods;
-- 獲取名稱之后就可以根據(jù)名稱來刪除外鍵約束
alter table goods drop foreign key 外鍵名稱;

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

三.數(shù)據(jù)庫的設計

創(chuàng)建 "商品分類" 表(之前已經(jīng)創(chuàng)建,無需再次創(chuàng)建)

create table goods_cates(
 id int unsigned primary key auto_increment not null,
 name varchar(40) not null
);

創(chuàng)建 "商品品牌" 表(之前已經(jīng)創(chuàng)建,無需再次創(chuàng)建)

create table goods_brands (
 id int unsigned primary key auto_increment not null,
 name varchar(40) not null
);

創(chuàng)建 "商品" 表(之前已經(jīng)創(chuàng)建,無需再次創(chuàng)建)

create table goods(
 id int unsigned primary key auto_increment not null,
 name varchar(40) default '',
 price decimal(5,2),
 cate_id int unsigned,
 brand_id int unsigned,
 is_show bit default 1,
 is_saleoff bit default 0,
 foreign key(cate_id) references goods_cates(id),
 foreign key(brand_id) references goods_brands(id)
);

創(chuàng)建 "顧客" 表

create table customer(
 id int unsigned auto_increment primary key not null,
 name varchar(30) not null,
 addr varchar(100),
 tel varchar(11) not null
);

創(chuàng)建 "訂單" 表

create table orders(
 id int unsigned auto_increment primary key not null,
 order_date_time datetime not null,
 customer_id int unsigned,
 foreign key(customer_id) references customer(id)
);

創(chuàng)建 "訂單詳情" 表

create table order_detail(
 id int unsigned auto_increment primary key not null,
 order_id int unsigned not null,
 goods_id int unsigned not null,
 quantity tinyint unsigned not null,
 foreign key(order_id) references orders(id),
 foreign key(goods_id) references goods(id)
);

說明

  • 以上創(chuàng)建表的順序是有要求的,即如果goods表中的外鍵約束用的是goods_cates或者是goods_brands,那么就應該先創(chuàng)建這2個表,否則創(chuàng)建goods會失敗
  • 創(chuàng)建外鍵時,一定要注意類型要相同,否則失敗

四.Python 中操作 MySQL 步驟

引入模塊

在py文件中引入pymysql模塊

from pymysql import *

Connection 對象

  • 用于建立與數(shù)據(jù)庫的連接
  • 創(chuàng)建對象:調用connect()方法
conn=connect(參數(shù)列表)
  • 參數(shù)host:連接的mysql主機,如果本機是'localhost'
  • 參數(shù)port:連接的mysql主機的端口,默認是3306
  • 參數(shù)database:數(shù)據(jù)庫的名稱
  • 參數(shù)user:連接的用戶名
  • 參數(shù)password:連接的密碼
  • 參數(shù)charset:通信采用的編碼方式,推薦使用utf8

對象的方法

  • close()關閉連接
  • commit()提交
  • cursor()返回Cursor對象,用于執(zhí)行sql語句并獲得結果

Cursor對象

  • 用于執(zhí)行sql語句,使用頻度最高的語句為select、insert、update、delete
  • 獲取Cursor對象:調用Connection對象的cursor()方法
cs1=conn.cursor()

對象的方法

  • close()關閉
  • execute(operation [, parameters ])執(zhí)行語句,返回受影響的行數(shù),主要用于執(zhí)行insert、update、delete語句,也可以執(zhí)行create、alter、drop等語句
  • fetchone()執(zhí)行查詢語句時,獲取查詢結果集的第一個行數(shù)據(jù),返回一個元組
  • fetchall()執(zhí)行查詢時,獲取結果集的所有行,一行構成一個元組,再將這些元組裝入一個元組返回

對象的屬性

  • rowcount只讀屬性,表示最近一次execute()執(zhí)行后受影響的行數(shù)
  • connection獲得當前連接對象

五.增刪改查

from pymysql import *

def main():
 # 創(chuàng)建Connection連接
 conn = connect(host='localhost',port=3306,database='jing_dong',user='root',password='mysql',charset='utf8')
 # 獲得Cursor對象
 cs1 = conn.cursor()
 # 執(zhí)行insert語句,并返回受影響的行數(shù):添加一條數(shù)據(jù)
 # 增加
 count = cs1.execute('insert into goods_cates(name) values("硬盤")')
 #打印受影響的行數(shù)
 print(count)

 count = cs1.execute('insert into goods_cates(name) values("光盤")')
 print(count)

 # # 更新
 # count = cs1.execute('update goods_cates set name="機械硬盤" where name="硬盤"')
 # # 刪除
 # count = cs1.execute('delete from goods_cates where id=6')

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

 # 關閉Cursor對象
 cs1.close()
 # 關閉Connection對象
 conn.close()

if __name__ == '__main__':
 main()

查詢一行數(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對象
 cs1 = conn.cursor()
 # 執(zhí)行select語句,并返回受影響的行數(shù):查詢一條數(shù)據(jù)
 count = cs1.execute('select id,name from goods where id>=4')
 # 打印受影響的行數(shù)
 print("查詢到%d條數(shù)據(jù):" % count)

 for i in range(count):
  # 獲取查詢的結果
  result = cs1.fetchone()
  # 打印查詢的結果
  print(result)
  # 獲取查詢的結果

 # 關閉Cursor對象
 cs1.close()
 conn.close()

if __name__ == '__main__':
 main()

查詢多行數(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對象
 cs1 = conn.cursor()
 # 執(zhí)行select語句,并返回受影響的行數(shù):查詢一條數(shù)據(jù)
 count = cs1.execute('select id,name from goods where id>=4')
 # 打印受影響的行數(shù)
 print("查詢到%d條數(shù)據(jù):" % count)

 # for i in range(count):
 #  # 獲取查詢的結果
 #  result = cs1.fetchone()
 #  # 打印查詢的結果
 #  print(result)
 #  # 獲取查詢的結果

 result = cs1.fetchall()
 print(result)

 # 關閉Cursor對象
 cs1.close()
 conn.close()

if __name__ == '__main__':
 main()

六.參數(shù)化

  • sql語句的參數(shù)化,可以有效防止sql注入
  • 注意:此處不同于python的字符串格式化,全部使用%s占位
from pymysql import *

def main():

 find_name = input("請輸入物品名稱:")

 # 創(chuàng)建Connection連接
 conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
 # 獲得Cursor對象
 cs1 = conn.cursor()


 # # 非安全的方式
 # # 輸入 " or 1=1 or " (雙引號也要輸入)
 # sql = 'select * from goods where name="%s"' % find_name
 # print("""sql===>%s<====""" % sql)
 # # 執(zhí)行select語句,并返回受影響的行數(shù):查詢所有數(shù)據(jù)
 # count = cs1.execute(sql)

 # 安全的方式
 # 構造參數(shù)列表
 params = [find_name]
 # 執(zhí)行select語句,并返回受影響的行數(shù):查詢所有數(shù)據(jù)
 count = cs1.execute('select * from goods where name=%s', params)
 # 注意:
 # 如果要是有多個參數(shù),需要進行參數(shù)化
 # 那么params = [數(shù)值1, 數(shù)值2....],此時sql語句中有多個%s即可 

 # 打印受影響的行數(shù)
 print(count)
 # 獲取查詢的結果
 # result = cs1.fetchone()
 result = cs1.fetchall()
 # 打印查詢的結果
 print(result)
 # 關閉Cursor對象
 cs1.close()
 # 關閉Connection對象
 conn.close()

if __name__ == '__main__':
 main()

以上就是MySQL和Python交互的示例的詳細內容,更多關于MySQL和python交互的資料請關注腳本之家其它相關文章!

相關文章

  • 快速解決mysql導數(shù)據(jù)時,格式不對、導入慢、丟數(shù)據(jù)的問題

    快速解決mysql導數(shù)據(jù)時,格式不對、導入慢、丟數(shù)據(jù)的問題

    這篇文章主要介紹了快速解決mysql導數(shù)據(jù)時,格式不對、導入慢、丟數(shù)據(jù)的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-07-07
  • Mysql樹形表的2種查詢解決方案(遞歸與自連接)

    Mysql樹形表的2種查詢解決方案(遞歸與自連接)

    MySQL作為一個關系型數(shù)據(jù)庫,存儲著許多的數(shù)據(jù)信息,在實際應用中經(jīng)常會遇到需要存儲樹形結構數(shù)據(jù)的情境,例如部門結構、商品分類等,這篇文章主要給大家介紹了關于Mysql樹形表的2種查詢解決方案,分別是遞歸與自連接,需要的朋友可以參考下
    2023-11-11
  • 淺談MySQL8和MySQL5.7在自增計數(shù)上的區(qū)別

    淺談MySQL8和MySQL5.7在自增計數(shù)上的區(qū)別

    MySQL數(shù)據(jù)庫是一款非常流行的開源數(shù)據(jù)庫,其版本升級迅速,在使用過程中也發(fā)現(xiàn)了不同版本之間存在著一些區(qū)別,本文主要介紹了MySQL8和MySQL5.7在自增計數(shù)上的區(qū)別,感興趣的可以了解一下
    2023-10-10
  • Mysql表批量添加字段一些示例代碼

    Mysql表批量添加字段一些示例代碼

    這篇文章主要給大家介紹了關于Mysql表批量添加字段的相關資料,在MySQL中可以使用ALTER TABLE語句來批量添加字段,下面這篇文章通過代碼介紹的非常詳細,需要的朋友可以參考下
    2024-04-04
  • MySQL 5.6 中 TIMESTAMP有那些變化

    MySQL 5.6 中 TIMESTAMP有那些變化

    前段時間,系統(tǒng)MySQL從5.5升級到了5.6,系統(tǒng)出現(xiàn)了大量的異常。大部分異常引起原因是由于TIMESTAMP的行為發(fā)生了變化,下面通過此篇文章給大家詳解MySQL 5.6 中 TIMESTAMP有那些變化,需要的朋友可以參考下
    2015-08-08
  • textarea標簽(存取數(shù)據(jù)庫mysql)的換行方法

    textarea標簽(存取數(shù)據(jù)庫mysql)的換行方法

    textarea標簽本身不識別換行功能,回車換行用的是\n換行符,輸入時的確有換行的效果,但是html渲染或者保存數(shù)據(jù)庫mysql時就只是一個空格了,這時就需要利用換行符\n和br標簽的轉換進行處理
    2023-09-09
  • mysqldump參數(shù)詳細說明及用途

    mysqldump參數(shù)詳細說明及用途

    ??mysqldump?? 是一個強大的工具,用于從 MySQL 數(shù)據(jù)庫中導出數(shù)據(jù),它支持多種輸出格式,包括 ??CSV??、??SQL??、??XML?? 等,在本文中,我們將詳細介紹 ??mysqldump?? 的一些常用參數(shù),以及它們的用途,感興趣的朋友一起看看吧
    2024-12-12
  • 詳解MySQL數(shù)據(jù)庫的安裝與密碼配置

    詳解MySQL數(shù)據(jù)庫的安裝與密碼配置

    本文主要對MySQL數(shù)據(jù)庫的安裝與密碼配置進行詳細介紹,具有一定的參考價值。下面就跟小編一起來看下吧
    2016-12-12
  • MySQL數(shù)據(jù)庫操作的基本命令

    MySQL數(shù)據(jù)庫操作的基本命令

    這篇文章主要介紹了MySQL使用初步之MySQL數(shù)據(jù)庫的基本命令,需要的朋友可以參考下
    2017-05-05
  • 什么是分表和分區(qū) MySql數(shù)據(jù)庫分區(qū)和分表方法

    什么是分表和分區(qū) MySql數(shù)據(jù)庫分區(qū)和分表方法

    這篇文章主要為大家詳細介紹了MySql數(shù)據(jù)庫分區(qū)和分表方法,告訴大家什么是分表和分區(qū),mysql分表和分區(qū)有什么聯(lián)系,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-02-02

最新評論

上犹县| 库伦旗| 清远市| 长子县| 酒泉市| 汾西县| 闸北区| 滨海县| 牡丹江市| 汉源县| 万盛区| 永善县| 中山市| 五莲县| 桓台县| 南江县| 旌德县| 浮山县| 张掖市| 正宁县| 伊川县| 阿拉善右旗| 巧家县| 枞阳县| 张北县| 宁南县| 来凤县| 永济市| 眉山市| 绥中县| 盐津县| 卢湾区| 灵川县| 安图县| 综艺| 桃园市| 临沭县| 尉犁县| 宿松县| 喜德县| 大同市|