【发布时间】:2014-02-05 13:03:43
【问题描述】:
这是从 Python 2.7 中的 SQL 查询中获取列表的正确方法吗?使用循环似乎有点虚假。有没有更简洁更好的方法?
import numpy as np
import pyodbc as SQL
from datetime import datetime
con = SQL.connect('Driver={SQL Server};Server=MyServer; Database=MyDB; UID=MyUser; PWD=MyPassword')
cursor = con.cursor()
#Function to convert the unicode dates returned by SQL Server into Python datetime objects
ConvertToDate = lambda s:datetime.strptime(s,"%Y-%m-%d")
#Parameters
Code = 'GBPZAR'
date_query = '''
SELECT DISTINCT TradeDate
FROM MTM
WHERE Code = ?
and TradeDate > '2009-04-08'
ORDER BY TradeDate
'''
#Get a list of dates from SQL
cursor.execute(date_query, [Code])
rows = cursor.fetchall()
Dates = [None]*len(rows) #Initialize array
r = 0
for row in rows:
Dates[r] = ConvertToDate(row[0])
r += 1
编辑:
当我想将查询放入结构化数组时怎么办?目前我做这样的事情:
#Initialize the structured array
AllData = np.zeros(num_rows, dtype=[('TradeDate', datetime),
('Expiry', datetime),
('Moneyness', float),
('Volatility', float)])
#Iterate through the record set using the cursor and populate the structure array
r = 0
for row in cursor.execute(single_date_and_expiry_query, [TradeDate, Code, Expiry]):
AllData[r] = (ConvertToDate(row[0]), ConvertToDate(row[1])) + row[2:] #Convert th0e date columns and concatenate the numeric columns
r += 1
【问题讨论】:
标签: python python-2.7 numpy pyodbc