【问题标题】:How to pass a date variable to an SQL query in Python如何将日期变量传递给 Python 中的 SQL 查询
【发布时间】:2016-07-25 23:32:52
【问题描述】:

Python3.5 Sql Server 2012 标准版

包是pypyodbc

此代码有效

myConnection = pypyodbc.connect('Driver={SQL Server};'
                                'Server=myserver;'
                                'Database=mydatabase;'
                                'TrustedConnection=yes')
myCursor = myConnection.cursor()
sqlstr = ("Select * From DB.Table1 Where DB.Table1.Date <= '7/21/2016'")
myCursor.execute(sqlstr)
results = myCursor.fetchall()

但是,Date 必须是用户传入的变量。我对 sqlstr 做了几个修改,但在 myCursor.execute 上继续出错:“TypeError: bytes or integer address expected instead of tuple instance”

sqlstr = ("Select * From DB.Table1 Where DB.Table1.Date <= %s", '7/21/2016')

错误

sqlstr = ("Select * From DB.Table1 Where DB.Table1.Date <= '%s'", '7/21/2016')

错误

sqlstr = ("Select * From DB.Table1 Where DB.Table1.Date <= ?", "'7/21/2016'")

错误

var1 = "'7/21/2016'"
sqlstr = ("Select * From DB.Table1 Where DB.Table1.Date <= %s", var1)

还有更多。但是,我确信有一种正确的方法...

感谢您的帮助!

【问题讨论】:

    标签: sql-server-2012 pydev python-3.5 pypyodbc


    【解决方案1】:

    我相信有一种正确的方法

    是的,这是一个参数化查询

    date_var = datetime(2016, 7, 21)
    sql = """\
    SELECT [ID], [LastName], [DOB] FROM [Clients] WHERE [DOB]<?
    """
    params = [date_var]  # list of parameter values
    crsr.execute(sql, params)
    for row in crsr.fetchall():
        print(row)
    

    【讨论】:

    • 谢谢,成功了。对于任何对多个参数感兴趣的人,只需用逗号分隔 [param1, param2, param3]。此外,我不必编辑要参数化的整个查询,只需将变量括在括号中。
    猜你喜欢
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    相关资源
    最近更新 更多