1. 程式人生 > >Python-資料庫操作-pymysql

Python-資料庫操作-pymysql

pymsql是Python中操作MySQL的模組,和之前使用的MySQLdb模組基本功能一致;
首先安裝pymysql,可使用pip來安裝,很方便,不過前提是按照pip以及有外網。
在cmd環境下執行:

pip install pymysql

pymysql的基本操作如下:

#!/usr/bin/env python
#   --coding = utf-8
#   Author Allen Lee
import pymysql

#建立連結物件

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123'
, db='Allen') #建立遊標 cursor = conn.cursor() #執行sql,更新單條資料,並返回受影響行數 effect_row = cursor.execute("update hosts set host = '1.1.1.2'") #插入多條,並返回受影響的函式 effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)",[("1.0.0.1",1,),("10.0.0.3",2)]) #獲取最新自增ID new_id = cursor.lastrowid #查詢資料
cursor.execute("select * from hosts") #獲取一行 row_1 = cursor.fetchone() #獲取多(3)行 row_2 = cursor.fetchmany(3) #獲取所有 row_3 = cursor.fetchall() #重設遊標型別為字典型別 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) #提交,儲存新建或修改的資料 conn.commit() #關閉遊標 cursor.close() #關閉連線 conn.close()