demo**樣例,暫時先寫查詢的,增刪改後續再新增;
無論是增刪改查,都需要先建立資料庫連線,建立游標
由於查出來的資料是從資料庫load到記憶體中,不用更改資料庫資料,所以不需要commit。import pymysql
#建立乙個mysql的conn,返回connetion物件
conn = pymysql.connect(
host =
'localhost'
, user =
'root'
, passwd =
'p@sswd'
, port =
'3306'
, db =
'test'
)#新建乙個游標,預設返還元組,可選dictcursor讓查詢結果返還dict
#為了方便後續get,我更喜歡查詢結果返還字典
cursor = conn.cursor(pymysql.cursors.dictcursor)
## 最後一定要記得釋放資源
"""todo 對資料庫的各種操作
"""cursor.close(
)conn.close(
)
增加的資料要修改資料庫,所以需要commit(python cursor 還有乙個很好用的東西,新增完了之後可以當場獲得自增id,而不用再寫select last_insert_id() 這種查詢語句獲得)##使用游標查詢資料
sql =
'select * from user'
query_result = cursor.execute(sql)
#query_result是int型別的,只顯示查詢了多少條,沒查到結果的話query_result=0,實際查詢結果資料在游標上
#檢視查詢結果,可以全部檢視fetchall()(返回dict組成的list),可以檢視一條fetchone()(返回乙個字典),還可以檢視n條,fetchmany(n)(返回n個字典組成的list)
if query_result:
for single_record in cursor.fetchall():
(single_record[
'name'],
'->'
,single_record[
'score'
]
sql =
'insert into user(name,age) values (%s,%s)'
data =[(
'lucy',24
),('june',20
),('jay',34
)]cursor.executemany(sql,data)
conn.commit(
)# 獲得新增記錄的自增id
last_id=cursor.lastrowid
Python操作mysql之模組pymysql
pymsql是python中操作mysql的模組,其使用方法和mysqldb幾乎相同。但目前pymysql支援python3.x而後者不支援3.x版本。本文環境 python3.6.1 mysql 5.7.18 1 安裝模組 pip3 install pymysql 2 python操作 1 獲取查...
PYTHON 之 常用模組
使用需要先導入 import calendar呼叫例子 calendar 獲取一年的日曆字串 引數 w 每個日期之間的間隔字元數 l 每週所占用的行數 c 每個月之間的間隔字元數 cal calendar.calendar 2017 print type cal print cal cal cale...
Python之常用模組
time模組 時間表示形式 1 時間戳 timestamp 通常來說,時間戳表示的是從1970年1月1日00 00 00開始按秒計算的偏移量。我們執行 type time.time 返回的是float型別。2 格式化的時間字串 format string 1988 09 29 3 元組 struct...