有时想更新或迁移部分SqlServer数据,用SQL只会整几句select,高级点的连个游标都玩不转有木有?拿起VS写个小程序不停的改又编译很烦,有木有?
想用脚本写了有木有?
本文介绍使用python,adodbapi操作数据库:
adodbapi 库
python 可以操作mssqlserver的类库有几个,支持python3.x的目前没几个靠谱的.adodbapi是使用ADO操作的.(不能跨平台?需要么?)
如:
'''
self.xlBook=self.xlApp.Workbooks.Open(filename)
sht = self.xlBook.Worksheets(sheet)
sht.Cells(row, col).Value = value
sht.Cells(row, col).Value = value
'''
详细过程:
首先添加引用:
import adodbapi
adodbapi.adodbapi.verbose = False # adds details to the sample printout
import adodbapi.ado_consts as adc
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)
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)
sql='''select * from softextBook where title='{0}' and remark3!='{1}'
'''.format(bookName,flag)
cur.execute(sql)
data=cur.fetchall()
cur.close()
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