python模塊之pyMySql

目錄:

  • 安裝
  • 使用

1、安裝

本模塊爲python第三方模塊,須要單獨安裝。做用爲調用mysql接口執行模塊python

pip3 install pyMySqlmysql

2、使用

一、執行SQLsql

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import pymysql
 4   
 5 # 建立鏈接
 6 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
 7 # 建立遊標
 8 cursor = conn.cursor()
 9   
10 # 執行SQL,並返回收影響行數
11 effect_row = cursor.execute("update hosts set host = '1.1.1.2'")
12   
13 # 執行SQL,並返回受影響行數
14 #effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))
15   
16 # 執行SQL,並返回受影響行數
17 #effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])
18   
19   
20 # 提交,否則沒法保存新建或者修改的數據
21 conn.commit()
22   
23 # 關閉遊標
24 cursor.close()
25 # 關閉鏈接
26 conn.close()
View Code

二、獲取新建立數據自增IDide

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import pymysql
 4   
 5 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
 6 cursor = conn.cursor()
 7 cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])
 8 conn.commit()
 9 cursor.close()
10 conn.close()
11   
12 # 獲取最新自增ID
13 new_id = cursor.lastrowid
View Code

三、獲取查詢數據fetch

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import pymysql
 4   
 5 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
 6 cursor = conn.cursor()
 7 cursor.execute("select * from hosts")
 8   
 9 # 獲取第一行數據
10 row_1 = cursor.fetchone()
11   
12 # 獲取前n行數據
13 # row_2 = cursor.fetchmany(3)
14 # 獲取全部數據
15 # row_3 = cursor.fetchall()
16   
17 conn.commit()
18 cursor.close()
19 conn.close()
View Code

注:在fetch數據時按照順序進行,能夠使用cursor.scroll(num,mode)來移動遊標位置,如:spa

  • cursor.scroll(1,mode='relative')  # 相對當前位置移動
  • cursor.scroll(2,mode='absolute') # 相對絕對位置移動

四、fetch數據類型code

關於默認獲取的數據是元祖類型,若是想要或者字典類型的數據,即:blog

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import pymysql
 4   
 5 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
 6   
 7 # 遊標設置爲字典類型
 8 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
 9 r = cursor.execute("call p1()")
10   
11 result = cursor.fetchone()
12   
13 conn.commit()
14 cursor.close()
15 conn.close()
View Code
相關文章
相關標籤/搜索