python學習第十一周【pymysql】
阿新 • • 發佈:2019-02-03
word close sel cal value nta last 信息 clas
一、安裝:pip3 install pymysql
使用操作
1、執行SQL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
# 創建連接
conn = pymysql. connect (host= ‘127.0.0.1‘ , port=3306, user = ‘root‘ , passwd= ‘123‘ , db= ‘t1‘ )
# 創建遊標
cursor = conn. cursor ()
# 執行SQL,並返回收影響行數 effect_row = cursor . execute ( "update hosts set host = ‘1.1.1.2‘" )
# 執行SQL,並返回受影響行數
#effect_row = cursor . execute ( "update hosts set host = ‘1.1.1.2‘ where nid > %s" , (1,))
# 執行SQL,並返回受影響行數
#effect_row = cursor .executemany( "insert into hosts(host,color_id)values(%s,%s)" , [( "1.1.1.11" ,1),( "1.1.1.11" ,2)])
# 提交,不然無法保存新建或者修改的數據
conn. commit ()
# 關閉遊標
cursor . close ()
# 關閉連接
conn. close ()
|
2、獲取新創建數據自增ID
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
conn = pymysql. connect (host= ‘127.0.0.1‘ , port=3306, user = ‘root‘ , passwd= ‘123‘ , db= ‘t1‘ )
cursor = conn. cursor ()
cursor .executemany( "insert into hosts(host,color_id)values(%s,%s)" , [( "1.1.1.11" ,1),( "1.1.1.11" ,2)])
conn. commit ()
cursor . close ()
conn. close ()
# 獲取最新自增ID
new_id = cursor .lastrowid
|
3、獲取查詢數據
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
conn = pymysql. connect (host= ‘127.0.0.1‘ , port=3306, user = ‘root‘ , passwd= ‘123‘ , db= ‘t1‘ )
cursor = conn. cursor ()
cursor . execute ( "select * from hosts" )
# 獲取第一行數據
row_1 = cursor .fetchone()
# 獲取前n行數據
# row_2 = cursor .fetchmany(3)
# 獲取所有數據
# row_3 = cursor .fetchall()
conn. commit ()
cursor . close ()
conn. close ()
|
註:在fetch數據時按照順序進行,可以使用cursor.scroll(num,mode)來移動遊標位置,如:
- cursor.scroll(1,mode=‘relative‘) # 相對當前位置移動
- cursor.scroll(2,mode=‘absolute‘) # 相對絕對位置移動
4、fetch數據類型
關於默認獲取的數據是元祖類型,如果想要或者字典類型的數據,即:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
conn = pymysql. connect (host= ‘127.0.0.1‘ , port=3306, user = ‘root‘ , passwd= ‘123‘ , db= ‘t1‘ )
# 遊標設置為字典類型
cursor = conn. cursor ( cursor =pymysql.cursors.DictCursor)
r = cursor . execute ( "call p1()" )
result = cursor .fetchone()
conn. commit ()
cursor . close ()
conn. close ()
|
作業: 參考表結構: 用戶類型 用戶信息 權限 用戶類型&權限 功能: # 登陸、註冊、找回密碼 # 用戶管理 # 用戶類型 # 權限管理 # 分配權限 特別的:程序僅一個可執行文件
python學習第十一周【pymysql】