一、簡(jiǎn)介
python可以連接數(shù)據(jù),方便開發(fā)對(duì)數(shù)據(jù)庫進(jìn)行批量操作,做性能測(cè)試時(shí),常常用來批量插入測(cè)試數(shù)據(jù)。
二、詳細(xì)說明
1.python操作數(shù)據(jù)庫流程:

2.引入包
? ?Python中連接mysql數(shù)據(jù)庫,需要import pymysql;
? ?Python中連接SqlServer數(shù)據(jù)庫,需要import pymssql;
3.生成connection對(duì)象
生成方法:pymysql.connect(host=?,?user=?, passwd=?) or?pymssql.connect(host=?,?user=?, passwd=?)?
connect方法參數(shù)列表:

#鏈接數(shù)據(jù)庫
server ="10.110.160.10:1111"
user ="XX"
password ="XXX"
connect = pymssql.connect(host=server, user=user, password=password)
connect對(duì)象的屬性:

4.生成cursor對(duì)象
游標(biāo)對(duì)象用于增刪改查和獲取結(jié)果,對(duì)數(shù)據(jù)庫的操作,需要游標(biāo)對(duì)象執(zhí)行。
生成游標(biāo)對(duì)象的方法:cursor = conntion.cursor()
游標(biāo)對(duì)象的屬性:

sql ="insert into common_service.dbo.USER_BASIC(ID,NM,ACC,UDD,MAIL,IND)values(%s,%s,%s,%s,%s,%d)"
try:
cursor.execute(sql, value)
connect.commit()
except Exception:
print("插入數(shù)據(jù)異常")
connect.rollback()
execute()在數(shù)據(jù)庫服務(wù)端執(zhí)行完成后,會(huì)將結(jié)果返回至客戶端緩存區(qū),fetch可以從緩存區(qū)讀取數(shù)據(jù)。

fetchone()?返回值為“(1,Name1)”
fetchmany(3)?返回值為(2,Name2),(3,Name3),(4,Name4)
fetchall()返回值為(5,Name5),(6,Name6)