python操作MySQL

#### 使用pymysql操作數(shù)據(jù)庫(kù)

##### 1、安裝

```

$ pip install pymysql

或者

$ python -m pip install pymysql

```

##### 2、操作

> 查詢操作

```

import pymysql

# 打開(kāi)數(shù)據(jù)庫(kù)連接

db = pymysql.connect("10.26.171.90","ism","Ism@123","ism_aggregation",charset="utf8")

# 使用cursor()方法獲取操作游標(biāo)

cursor = db.cursor()

# SQL 查詢語(yǔ)句

sql = "SELECT * FROM t_fund_info limit 10"

try:

? # 執(zhí)行SQL語(yǔ)句

? cursor.execute(sql)

? # 獲取所有記錄列表

? results = cursor.fetchall()

? for row in results:

? ? ? vc_fund_id = row[0]

? ? ? vc_fund_name = row[1]

? ? ? vc_fund_simple_name = row[2]

except:

? print ("Error: unable to fetch data")

# 關(guān)閉數(shù)據(jù)庫(kù)連接

db.close()

```

- fetchone(): 獲取第一行數(shù)據(jù)。結(jié)果集是一個(gè)對(duì)象

- fetchmany(N): 獲取前N行數(shù)據(jù)

- fetchall(): 獲取所有返回結(jié)果

```

游標(biāo)類型默認(rèn)為元組,可以設(shè)置為其他形式

字典形式:

cur = db.cursor(cursor=pymysql.cursors.DictCursor)

```

> 增刪改

db.commit()后才會(huì)更新到數(shù)據(jù)庫(kù)追蹤

```

import pymysql

# 打開(kāi)數(shù)據(jù)庫(kù)連接

db = pymysql.connect(host='xxx',port= 3306,user = 'xxx',passwd='xxx',db='xxx')

# 使用cursor()方法獲取操作游標(biāo)

cursor = db.cursor()

# SQL 更新語(yǔ)句

sql = "INSERT INTO t_fund_info(fund_id, fund_name, a, b, c, d, e, f, g, h, i, j) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (id, name, a_value, b_value, c, d, e, f, g, h, i, j)

try:

? # 執(zhí)行SQL語(yǔ)句

? cursor.execute(sql)

? # 提交到數(shù)據(jù)庫(kù)執(zhí)行

? db.commit()

except:

? # 發(fā)生錯(cuò)誤時(shí)回滾

? db.rollback()

# 關(guān)閉數(shù)據(jù)庫(kù)連接

db.close()

```

##### 3、游標(biāo)操作

```

在fetch數(shù)據(jù)時(shí)按照順序進(jìn)行,可以使用cursor.scroll(num,mode)來(lái)移動(dòng)游標(biāo)位置,如:

cursor.scroll(1,mode='relative') # 相對(duì)當(dāng)前位置移動(dòng)

cursor.scroll(2,mode='absolute') # 相對(duì)絕對(duì)位置移動(dòng)

```

##### 4、調(diào)用存儲(chǔ)過(guò)程

```

#無(wú)參數(shù)存儲(chǔ)過(guò)程

cursor.callproc('p1')? #等價(jià)于cursor.execute("call p1()")

#有參數(shù)存儲(chǔ)過(guò)程

cursor.callproc('p2', args=(1, 2, 3, 4))

#獲取執(zhí)行完存儲(chǔ)的參數(shù),參數(shù)@開(kāi)頭

cursor.execute("select @p2,@_p2_1,@_p2_2,@_p2_3")

```

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容