pyodbc使用

pyodbc是用于访问ODBC数据库的python模块。
1、安装
pip install pyodbc
2、连接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')
3、常用操作
一般都是通过游标进行操作
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)
4、参考
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.html

猜你喜欢

转载自www.cnblogs.com/hepc/p/9434470.html
今日推荐