使用python執行sql語句和外鍵解析


一、下載並導入pymysql

pip install pymysql && import pymysql

   db=pymysql.connect(host='192.168.253.10',user='root',password='1',db='mysql',port=3306)   #如果報錯host大概率因為沒設置允許第三方登陸
cur=db.cursor()
cur.execute('show tables;')             #注意execute書寫
db.commit()                                  #提交才生效
result=cur.fetchall()                   #取數據,fetchone(n)獲取下表對應的數據
print(result)

實驗:用python執行sql語句測試時間

1)

import pymysql
db=pymysql.connect(host='192.168.253.10',user='root',password='1',db='zzz',port=3306)
cur=db.cursor()
for i in range(1000):                         
    print(i)                 
    cur.execute("insert into ss values(0,'name-%s')"%i)       #必須用雙引號
db.commit()                  #必須提交事務,否則無效,並且置頂格,將所有循壞寫入的步驟當作一個事務提交。
result=cur.fetchall()
print(result)

2) python執行完畢后,去linux主機登陸查看是否插入成功。

MariaDB [zzz]> select count(*) from ss;
+----------+
| count(*) |
+----------+
| 1000 |
+----------+

或者 select * from ss  limit  10;                 #注意分頁查看,因為插入數據多

3) 查看profiling的狀態,,如果是off改成ON

show variables  status like  '%profiling%' ;

+------------------------+-------+
| Variable_name          | Value |
+------------------------+-------+
| have_profiling         | YES   |     
| profiling              | off    |     
| profiling_history_size | 15    |

臨時性更改:set profiling =1;                  #重啟等會重置

永久性更改,寫進/etc/my.cnf.d/server.cnf 的server模塊下。

4)執行命令查看profiles狀態的duration列,然后添加索引后執行相同命令再來查看,對比前后耗時,可以得知索引的作用。

MariaDB [zzz]> show profiles;
+----------+------------+----------------------------------------+
| Query_ID | Duration   | Query                                  |
+----------+------------+----------------------------------------+
|        1 | 0.00319622 | show variables like '%profiling%'      |
|        5 | 0.00165140 | select * from ss where name='name-123' |     此步驟時間同8作比較
|        6 | 0.00026767 | show profiling                         |
|        7 | 0.02831208 | create index n_i on ss(name)           |      #創建完索引后
|        8 | 0.00090224 | select * from ss where name='name-123'   此步驟時間同5作比較發現快了幾十倍,插入量越多效果越明顯

至此,python執行sql語句實驗完成。

二、外鍵

  • 如果一個實體的某個字段指向另一個實體的主鍵,就稱為外鍵。被指向的實體,稱之為主實體(主表),也叫父實體(父表)。負責指向的實體,稱之為從實體(從表),也叫子實體(子表)

  • 對關系字段進行約束,當為從表中的關系字段填寫值時,會到關聯的主表中查詢此值是否存在,如果存在則填寫成功,如果不存在則填寫失敗並報錯

#添加外鍵

alter table 子表名 add  constraint  外鍵名  foreign key (關鍵詞)  references  夫表名(對應關鍵詞);  

#刪除外鍵

alter table students drop foreign key 外鍵名字;

在學生表上創建外鍵指向班級表(表見上一博客)

MariaDB [zzz]> alter table students add constraint fk foreign key(cls_id) references classes(id); 
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`zzz`.`#sql-acc_13`, CONSTRAINT `fk` FOREIGN KEY (`cls_id`) REFERENCES `classes` (`id`))

此報錯是因為外鍵的約束作用,學生表的id有3、4、5但是班級表的id只有1,2;解決此報錯要么學生表刪除id為{3,4,5}的數據,要么增加班級表id為3,4,5的數據(總之使兩個表的id對應上)

我們這里選擇刪除學生表的3,4,5數據
MariaDB [zzz]> delete from students where id >2;
Query OK, 15 rows affected (0.003 sec)

再執行:

alter table students add constraint fk foreign key(cls_id) references classes(id) ;   

show create table  students(子表名);     #查看外鍵是否添加成功

 同理,只要兩個表之間添加了外鍵約束,插入、修改刪除、數據都會受彼此約束。

 

例如,由於父表id只有1和2,我們現在往子表students里面添加數據:

MariaDB [zzz]> insert into students values(0,'小明',18,180.00,2,3,0);       #插入id=3報錯
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`zzz`.`students`, CONSTRAINT `fk` FOREIGN KEY (`cls_id`) REFERENCES `classes` (`id`))

解決方法為,先添加父表的id=3的數據。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM