Python操做MySQL之pymysql

pymsql是Python中操做MySQL的模塊,其使用方法和MySQLdb幾乎相同。python

安裝

只是一個第三方庫而已:
pip3 install pymysqlmysql

使用

執行SQL語句

import pymysql

#建立鏈接
conn = pymysql.connect(host='192.168.4.193', user='cc', passwd='123', db='cc')
#常見遊標
cursor = conn.cursor()
#執行SQL,並返回受影響的行數
effect_row = cursor.execute(" select * from tt ")

# effect_row_1 = cursor.execute("alter TABLE tt ADD host char(30)")

#也能夠字符串替換,後面是元組類型參數
cursor.execute("update tt SET host = '1.1.0.7' WHERE nid <%s ",(3,))

#多個%s爲後面的爲列表類型
#cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])

print(effect_row)
#提交,否則沒法保存新建或者修改的數據
conn.commit()
#關閉遊標
cursor.close()
#關閉鏈接
conn.close()

獲取新建立數據自增ID

import pymysql

#建立鏈接
conn = pymysql.connect(host='192.168.4.193', user='cc', passwd='123', db='cc')
#常見遊標
cursor = conn.cursor()
#執行SQL,並返回受影響的行數
effect_row = cursor.execute(" select * from tt ")

# effect_row_1 = cursor.execute("alter TABLE tt ADD host char(30)")

#也能夠字符串替換,後面是元組類型參數
cursor.execute("update tt SET host = '1.1.0.7' WHERE nid <%s ",(3,))

#多個%s爲後面的爲列表類型
#cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])

print(effect_row)
#提交,否則沒法保存新建或者修改的數據
conn.commit()
#關閉遊標
cursor.close()
#關閉鏈接
conn.close()

獲取查詢數據

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)來移動遊標位置,如:sql

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

fech的數據類型

默認獲取的數據是元祖類型,若是想要獲取字典類型的數據,能夠這樣:fetch

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()

獲取新建立數據自增ID

#!/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
相關文章
相關標籤/搜索