【发布时间】:2019-08-23 17:01:37
【问题描述】:
我正在尝试在 Python 中做这样的事情,
SQLCommand = ("Delete From %s where [Date] >= %s and [Date] <= %s", (calendar_table_name, required_starting_date, required_ending_date))
cursor.execute(SQLCommand)
calendar_table_name 是一个string 变量
required_starting_date 是一个datetime 变量
required_ending_date 是一个datetime 变量
尝试这样做会给我一个错误:
要执行的第一个参数必须是字符串或 unicode 查询。
试过这个,它给了我同样的错误:
SQLCommand = ("Delete From " + calendar_table_name + " where [Date] >= %s and [Date] <= %s", ( required_starting_date, required_ending_date))
cursor.execute(SQLCommand)
编辑:
type(required_ending_date)
Out[103]: pandas._libs.tslibs.timestamps.Timestamp
type(required_starting_date)
Out[103]: pandas._libs.tslibs.timestamps.Timestamp
这对我来说适用于 SSMS,
delete from [table_test] where [Date] >= '2007-01-01' and [Date] <= '2021-01-01';
更新:- 这是我正在尝试的代码
Delete_SQLCommand = f"Delete FROM [{calendar_table_name}] WHERE [Date]>=? And [Date]<=?"
params = (required_starting_date, required_ending_date)
required_starting_date 和 required_ending_date 是“时间戳”格式
calendar_tbl_connection = pyodbc.connect(driver=driver, server=required_server, database=database_name,
trusted_connection='yes')
calendar_tbl_cursor = calendar_tbl_connection.cursor()
calendar_tbl_cursor.execute(Delete_SQLCommand,params)
calendar_tbl_connection.commit
calendar_tbl_connection.close()
【问题讨论】:
-
您不能参数化表名。
From %s where在这种情况下无效。您需要使用字符串格式来制作动态表名,然后为查询的其余部分传递参数 -
你还没有向我们展示这个 sql 命令是如何使用的。给我们打电话给
execute()。 -
对,所以编辑建议您传递
datetime对象而不是字符串,并且该列配置为采用 TEXT 值(或类似值),或者您的连接库不会转换成 ISO 格式 -
@tgikal 这就是您获得 SQL 注入攻击的方式。不要那样做。
-
使
SQLCommand成为字符串部分,即SQLCommand = "Delete From ..."。然后使用参数调用执行:cursor.execute(SQLCommand, (arg1, arg2))
标签: python sql-server pandas pyodbc