简体   繁体   English

在 Python 中写入 SQL 语句时出现列名无效的错误

[英]Getting error that invalid column name while writing SQL statement in Python

I am trying to write a SQL statement in Python: 'attribute' is a column name that I want to change its format and I am giving it as a parameter.我正在尝试在 Python 中编写 SQL 语句:“属性”是我想更改其格式的列名,我将其作为参数提供。 Because its name can be different.因为它的名字可以不同。

cur.execute("SELECT DATEADD(y," + attribute + ", '1980-01-01')")

But I am getting below error.但我得到了错误。 attribute=Date1 and this column exists.属性=Date1 并且该列存在。

[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'Date1'. [42S22] [Microsoft][用于 SQL 服务器的 ODBC 驱动程序 17][SQL Server]列名“Date1”无效。 (207) (SQLExecDirectW)" (207) (SQLExecDirectW)"

If I understand your code correctly, you're building the string in the cur.execute command.如果我正确理解了您的代码,那么您将在cur.execute命令中构建字符串。 If your python is up-to-date, try using fstrings .如果您的 python 是最新的,请尝试使用fstrings They are a bit more readable and you don't get the messy code with all the quotes.它们更具可读性,并且您不会得到带有所有引号的凌乱代码。 If your python version doesn't support substrings, try building the request in a variable to make the code a bit more readable.如果您的 python 版本不支持子字符串,请尝试在变量中构建请求以使代码更具可读性。
Possible solution:可能的解决方案:
cur.execute(f"SELECT DATEADD(y, {attribute}, '1980-01-01')")
The string will result in SELECT DATEADD(y, Date1, '1980-01-01')该字符串将导致SELECT DATEADD(y, Date1, '1980-01-01')
There is also a FROM missing from the query, the error Invalid column is correct because you don't tell where to find that column查询中还缺少FROM ,错误Invalid column是正确的,因为您不知道在哪里可以找到该列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM