【问题标题】:fetchone() returns none despite the query retrieving data尽管查询检索数据,但 fetchone() 不返回任何内容
【发布时间】:2018-06-11 20:26:11
【问题描述】:

我正在为检查我的数据库中的值的方法编写单元测试。我写了以下内容:

# Runs SQL query to check if price exists for base date
# If it exists, set the base price to that value
# If it doesn't, set it to 100
def get_base_price(self, month):
    sql = '''SELECT COALESCE(TimeSeriesValue, 100) as TimeSeriesValue
        FROM [RAP].[dbo].[TimeSeriesPosition]
        WHERE TimeSeriesTypeID = 12 AND
              SecurityMasterID = 45889 AND
              FundID = 7 AND
              EffectiveDate = %s''' % month
    with self.job.rap.connect() as conn:
        data = conn.execute(sql).fetchone()
        print(sql)
    return data  # Returns base price value

这是测试:

# test to grab a base price
def test_retrieving_base_price_if_month_exists(self):
    base_price = self.parser.get_base_price('1990-12-31')
    self.assertEqual(base_price, 108.692339086277)

注意:self.parser 是包含方法的导入类。

我在方法中打印了 SQL 查询,它正在正确执行。我猜问题出在我执行查询的方式上。我似乎无法弄清楚为什么它返回无。它应该返回一行,我稍后可以使用 [0] 获取它的值。

【问题讨论】:

    标签: python sql-server


    【解决方案1】:

    SQL 查询运行的是不带引号的日期:

    1990-12-31

    我必须添加三引号并将字符串变量用单引号括起来。那行得通。

    【讨论】:

    • 你应该使用游标和准备好的语句而不是字符串替换。
    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 2012-04-14
    • 2014-05-02
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    相关资源
    最近更新 更多