pyodbc使用

pyodbc是用於調用ODBC數據庫接口而封裝的python模塊。
一、安裝
pip install pyodbc
二、鏈接DB
#指定Driver鏈接
connection = pyodbc.connect('Driver={ODBC Driver 13 for SQL Server};Server=XXX;database=XXX;uid=XXX;pwd=XXX')
#經過DSN鏈接(須要先配置)
connection = pyodbc.connect('DSN=MSSQL-ABC;Server=XXX;database=XXX;uid=XXX;pwd=XXX')
三、經常使用操做
通常都是經過遊標進行操做
cursor = connection.cursor()
(1)select
rows=cursor.execute("SELECT * FROM dbo.RecognisePhoto WHERE RecogStatus=0 AND Cate=2;")
注意:select必須爲第一條語句,一次執行不能同時返回多個select結果集;不能使用commit()
"錯誤 cursor.execute('SELECT TOP 1000 VenderId,PhotoId INTO #tmpInPhoto FROM dbo.RecognisePhoto WHERE RecogStatus=0 AND Cate=2;SELECT * FROM #tmpInPhoto;')「
(2)update、insert及delete須要持久化的操做
多條能夠一塊兒執行
cursor.execute('UPDATE RecognisePhoto SET RecogStatus=0 WHERE RecogStatus=-1;UPDATE RecognisePhoto SET RecogStatus=-1 WHERE RecogStatus=0 AND Cate=2;')
必須提交事務不然會產生事務鎖
cursor.commit()
出現異常時回滾
conn.rollback()
(3)既帶select又帶須要持久化操做的如update的語句,不能放在同一個執行裏,可分多個execute或採用存儲過程
此種類型的存儲過程的執行方式必須爲execute().fetchall()並commit()
rows=cursor.execute('EXEC dbo.PR_GetRecogData @cate = %d,@num = %d ;'%(2,100)).fetchall()
cursor.commit()
(4)遍歷結果
經過遊標捉個遍歷
row = cursor.fetchone()
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()
返回全部行再遍歷
for row in rows:
print(row)
(5)批量執行executemany
批量插入
sql = 'INSERT INTO 表名 VALUES(%s,%s,%s)' #無論什麼類型,統一使用%s做爲佔位符
param = ((username1, salt1, pwd1), (username2, salt2, pwd2), (username3, salt3, pwd3)) #對應的param是一個tuple或者list
n=cursor.executemany(sql,param)
四、參考
pyodbc的簡單使用
https://blog.csdn.net/u013013708/article/details/51086665
遭瘟的pyodbc——關於存儲過程執行
https://blog.csdn.net/samed/article/details/49963531
MySQLdb使用批量插入executemany方法插入mysql
https://www.cnblogs.com/zoro-robin/p/6852409.htmlhtml

相關文章
相關標籤/搜索