3

我正在尝试使用 sqlalchemy 从我的 Python 代码中调用 SQL Server 存储过程。我发现python代码没有引发错误,并且存储过程没有执行。

示例代码:

def SaveData(self, aScrapeResult):
    sql = "EXECUTE mc.SaveFundamentalDataCSV @pSource='%s',@pCountry='%s',@pOperator='%s',@pFromCountry='%s',@pFromOperator='%s',@pToCountry='%s',@pToOperator='%s',@pSiteName='%s',@pFactor='%s',@pGranularity='%s',@pDescription='%s',@pDataType='%s',@pTechnology = '%s',@pcsvData='%s'"

    #   Need to convert the data into CSV
    util = ListToCsvUtil()
    csvValues = util.ListToCsv(aScrapeResult.DataPoints)

    formattedSQL = sql % (aScrapeResult.Source ,aScrapeResult.Country,aScrapeResult.Operator ,aScrapeResult.FromCountry ,aScrapeResult.FromOperator ,aScrapeResult.ToCountry ,aScrapeResult.ToOperator ,aScrapeResult.SiteName ,aScrapeResult.Factor ,aScrapeResult.Granularity ,aScrapeResult.Description ,aScrapeResult.DataType ,aScrapeResult.Technology ,csvValues)

    DB = create_engine(self.ConnectionString)
    DB.connect()

    result_proxy = DB.execute(formattedSQL)

    results = result_proxy.fetchall()

检查格式化的 SQL 产生以下命令

EXECUTE mc.SaveFundamentalDataCSV @pSource='PythonTest', @pCountry='UK',
  @pOperator='Operator', @pFromCountry='None', @pFromOperator='None', 
  @pToCountry='None', @pToOperator='None', @pSiteName='None', @pFactor='Factor', 
  @pGranularity='Hourly', @pDescription='Testing from python', 
  @pDataType='Forecast',@pTechnology = 'Electricity',
  @pcsvData='01-Jan-2012 00:00:00,01-Feb-2012 00:15:00,1,01-Jan-2012 00:00:00,01-Feb-2012 00:30:00,2';

使用的各种版本和软件如下: SQL Server 2008 R2 Python 2.6.6 SQLAlchemy 0.6.7

我已经通过使用相同参数直接在 SQL Server Management Studio 中调用它来测试我的存储过程,没有问题。

值得一提的是,这点 Python 版本和 SQL server 版本是不可更改的。我对 sqlalchemy 没有强烈的忠诚度,并对其他建议持开放态度。

任何建议将不胜感激,如果需要,可以提供更多信息。

4

1 回答 1

2

现在已修复,但如果我在这里使用最佳实践,请接受意见。我使用了 sqlalchemy 公开的“文本”对象,工作代码如下:

def SaveData(self, aScrapeResult):
    sql = "EXECUTE mc.SaveFundamentalDataCSV @pSource='%s',@pCountry='%s',@pOperator='%s',@pFromCountry='%s',@pFromOperator='%s',@pToCountry='%s',@pToOperator='%s',@pSiteName='%s',@pFactor='%s',@pGranularity='%s',@pDescription='%s',@pDataType='%s',@pTechnology = '%s',@pcsvData='%s'"

    #   Need to convert the data into CSV
    util = ListToCsvUtil()
    csvValues = util.ListToCsv(aScrapeResult.DataPoints)

    formattedSQL = sql % (aScrapeResult.Source ,aScrapeResult.Country,aScrapeResult.Operator ,aScrapeResult.FromCountry ,aScrapeResult.FromOperator ,aScrapeResult.ToCountry ,aScrapeResult.ToOperator ,aScrapeResult.SiteName ,aScrapeResult.Factor ,aScrapeResult.Granularity ,aScrapeResult.Description ,aScrapeResult.DataType ,aScrapeResult.Technology ,csvValues)

    DB = create_engine(self.ConnectionString)
    conn = DB.connect()

    t = text(formattedSQL).execution_options(autocommit=True)

    DB.execute(t)

    conn.close()

希望这对其他人有帮助!

于 2012-09-19T08:50:21.123 回答