前几天因为业务需求,需要在Windows下读取sdf文件,对于没做过 Windows开发的我,只能想到python去实现,但是又不知道怎么做,于是查各种资料,最后在同事的帮助下,终于得到了答案,现将实现过程做如下分享。
一,软件安装:
1,安装python2.7
2,配置python和pip环境变量
3,安装pywin32库(下载地址:https://sourceforge.net/projects/pywin32/files/pywin32/Build%20221/)需要和python版本相对应,如果import adodbapi出错,需要执行pip install adodbapi --upgrade
4,本地已经安装了sqlServer compect文件数据库。
二,代码部分
# -*- coding: utf-8 -*-
import adodbapi
from adodbapi import connect
import win32com.client
import pythoncom
import csv
import datetime
import time
class dataProcess:
def __init__(self):
# 获取当前时间前5分钟数据
self.dataTime = ((datetime.datetime.now() - datetime.timedelta(minutes=5)).strftime("%Y-%m-%d %H:%M"))
self.dataTime1 = ((datetime.datetime.now() - datetime.timedelta(minutes=5)).strftime("%Y%m%d%H%M"))
def processData(self):
pythoncom.CoInitialize()
win32com.client.Dispatch('ADODB.Connection')
sdfile = "C:\Users\Public\AppData\TSM100\Server0\Results.sdf"
connstr = 'Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5; Mode = ReadWrite; SSCE:Max Database Size=3999;Persist Security Info=False;Data Source=' + sdfile
conn = adodbapi.connect(connstr)
cur = conn.cursor()
sql = "select Timestamp,Code,CAST(message as ntext) as message,CAST(TransportId AS ntext) AS TransportId from AnalysisError where code=10 and Timestamp>'%s' " % (
self.dataTime)
cur.execute(sql)
filename = "D:\\baishitongData\\resultFlie\\result%s.csv" % (self.dataTime1)
with open(filename.decode('utf-8'), "w") as csvfile:
for res in cur.fetchall():
writer = csv.writer(csvfile)
writer.writerows([res])
conn.close()
if __name__ == "__main__":
while True:
nDataProcess = dataProcess();
nDataProcess.processData();
break
以上代码实现了使用adodbapi库连接了sdf文件数据库,并将数据取出来放到csv文件保存。