adodbapi 库

本文介绍如何利用Python和adodbapi库操作MSSQL数据库,包括创建连接、执行SQL语句和存储过程,以及关闭连接的过程。通过示例代码,展示了如何使用Python进行数据库操作,简化了数据迁移和更新的工作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

开启阅读模式

使用Python操作MSSQL数据库.

有时想更新或迁移部分SqlServer数据,用SQL只会整几句select,高级点的连个游标都玩不转有木有?拿起VS写个小程序不停的改又编译很烦,有木有?

想用脚本写了有木有?

本文介绍使用python,adodbapi操作数据库:

adodbapi 库
python 可以操作mssqlserver的类库有几个,支持python3.x的目前没几个靠谱的. adodbapi是使用ADO操作的.(不能跨平台?需要么?)
所以首先要安装  

Python for Windows extensions

    ,有了pywin32这个扩展可以做很多事,用它操作EXCEL等,甚至比VBScript还要简洁
如:
'''
     self.xlBook=self.xlApp.Workbooks.Open(filename)
     sht = self.xlBook.Worksheets(sheet)   
      sht.Cells(row, col).Value = value 
'''
详细过程:


首先添加引用:
import adodbapi
adodbapi.adodbapi.verbose = False # adds details to the sample printout
import adodbapi.ado_consts as adc
创建连接:
    Cfg={'server':'192.168.29.86\\eclexpress','password':'xxxx','db':'pscitemp'}
    constr = r"Provider=SQLOLEDB.1; Initial Catalog=%s; Data Source=%s; user ID=%s; Password=%s; " \
         % (Cfg['db'], Cfg['server'], 'sa', Cfg['password'])
    conn=adodbapi.connect(constr)
其中Cfg是个key-value字典,constr格式化语法是python2.x常用,在3.x可以使用下面的.
执行sql语句:
    cur=conn.cursor()
    sql='''select * from softextBook where title='{0}' and remark3!='{1}'
    '''.format(bookName,flag)
    cur.execute(sql)
    data=cur.fetchall()
    cur.close()
其中三个引号类似于C#字符串前的"@",python中字符串可以用一个或两个,三个括起来,format格式化语法也类似
执行存储过程:
     #假设proName有三个参数,最后一个参数传了null
    ret=cur.callproc('procName',(parm1,parm2,None))
    conn.commit()
关闭连接
conn.close()
很简单有木有?
更多代码示例见安装目录下里的unit test代码:
C:\Python31\Lib\site-packages\adodbapi\tests
com_error Traceback (most recent call last) File D:\anaconda3\Lib\site-packages\adodbapi\adodbapi.py:91, in connect(*args, **kwargs) 90 try: # connect to the database, using the connection information in kwargs ---> 91 co.connect(kwargs) 92 return co File D:\anaconda3\Lib\site-packages\adodbapi\adodbapi.py:266, in Connection.connect(self, kwargs, connection_maker) 265 try: --> 266 self.connector.Open() # Open the ADO connection 267 except api.Error: File <COMObject ADODB.Connection>:2, in Open(self, ConnectionString, UserID, Password, Options) File D:\anaconda3\Lib\site-packages\win32com\client\dynamic.py:355, in CDispatch._ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *args) 354 def _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *args): --> 355 result = self._oleobj_.InvokeTypes( 356 *(dispid, LCID, wFlags, retType, argTypes) + args 357 ) 358 return self._get_good_object_(result, user, resultCLSID) com_error: (-2147352567, '发生意外。', (0, 'ADODB.Connection', '未找到提供程序。该程序可能未正确安装。', 'C:\\Windows\\HELP\\ADO270.CHM', 1240655, -2146824582), None) During handling of the above exception, another exception occurred: OperationalError Traceback (most recent call last) Cell In[3], line 6 4 import numpy as np 5 import matplotlib.pyplot as plt ----> 6 from adodbapi.examples.xls_read import sheet File D:\anaconda3\Lib\site-packages\adodbapi\examples\xls_read.py:25 21 filename = "xx.xls" 23 constr = "Provider=%s;Data Source=%s;%s" % (driver, filename, extended) ---> 25 conn = adodbapi.connect(constr) 27 try: # second command line argument will be worksheet name -- default to first worksheet 28 sheet = sys.argv[2] File D:\anaconda3\Lib\site-packages\adodbapi\adodbapi.py:95, in connect(*args, **kwargs) 93 except Exception as e: 94 message = 'Error opening connection to "%s"' % co.connection_string ---> 95 raise api.OperationalError(e, message) OperationalError: (com_error(-2147352567, '发生意外。', (0, 'ADODB.Connection', '未找到提供程序。该程序可能未正确安装。', 'C:\\Windows\\HELP\\ADO270.CHM', 1240655, -2146824582), None), 'Error opening connection to "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=-f;Extended Properties="Excel 8.0;HDR=Yes;IMEX=1;""')
最新发布
08-13
C:\Users\lianb>pip install adodbapi Collecting adodbapi Using cached adodbapi-2.6.2.0.zip (297 kB) Installing build dependencies ... done Getting requirements to build wheel ... error error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [31 lines of output] adodbapi version="2.6.2.0" Traceback (most recent call last): File "<string>", line 51, in setup_package ImportError: cannot import name 'build_py_2to3' from 'distutils.command.build_py' (C:\Users\lianb\AppData\Local\Temp\pip-build-env-qdwwlild\overlay\Lib\site-packages\setuptools\_distutils\command\build_py.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Python\Python313\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 389, in <module> main() ~~~~^^ File "D:\Python\Python313\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 373, in main json_out["return_val"] = hook(**hook_input["kwargs"]) ~~~~^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python\Python313\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 143, in get_requires_for_build_wheel return hook(config_settings) File "C:\Users\lianb\AppData\Local\Temp\pip-build-env-qdwwlild\overlay\Lib\site-packages\setuptools\build_meta.py", line 334, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=[]) ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lianb\AppData\Local\Temp\pip-build-env-qdwwlild\overlay\Lib\site-packages\setuptools\build_meta.py", line 304, in _get_build_requires self.run_setup() ~~~~~~~~~~~~~~^^ File "C:\Users\lianb\AppData\Local\Temp\pip-build-env-qdw
03-22
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值