query.format没有参数时,如何使用pyodbc、cursor、execute从SQL中提取数据?
How to use pyodbc, cursor, execute to extract data from SQL when there is no parameters for query.format?
通常,我使用以下方式从SQL中提取数据使用Python:
myConnect=pyodbc.connect('DSN=B1P HANA;UID=****;PWD=****')
myCursor=myConnect.cursor()
Start1=20150101
End=20200101
query = """
SELECT "Operator",
"Position"
FROM ******
"""
myRow = myCursor.execute(query.format(Start1=Start1,
End=End)
Result = myRow.fetchall()
OperatorTMs = pd.DataFrame(columns=["Operator", "Position"])
for i in Result:
OperatorTMs=OperatorTMs.append({"Operator":i.Operator,"Position":i.Position},ignore_index=True)
但是现在,我不需要 query.format() 中的任何参数。我尝试了https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html中的方法。而且它不起作用
那么,如何在 query.format 中不使用任何参数来执行此操作?
您真的不应该使用 .format
将列值插入到您的 SQL 命令中。搜索 "SQL Injection" 或 "Little Bobby Tables" 以获取更多信息。
相反,您应该使用 ?
参数占位符并将列值作为附加参数提供给 .execute
,如
query = "SELECT col1, col2 FROM tablename WHERE col1 BETWEEN ? AND ?"
myRow = myCursor.execute(query, Start1, End)
对于没有参数值的查询,您只需单独传递 query
字符串
query = "SELECT col1, col2 FROM tablename"
myRow = myCursor.execute(query)
通常,我使用以下方式从SQL中提取数据使用Python:
myConnect=pyodbc.connect('DSN=B1P HANA;UID=****;PWD=****')
myCursor=myConnect.cursor()
Start1=20150101
End=20200101
query = """
SELECT "Operator",
"Position"
FROM ******
"""
myRow = myCursor.execute(query.format(Start1=Start1,
End=End)
Result = myRow.fetchall()
OperatorTMs = pd.DataFrame(columns=["Operator", "Position"])
for i in Result:
OperatorTMs=OperatorTMs.append({"Operator":i.Operator,"Position":i.Position},ignore_index=True)
但是现在,我不需要 query.format() 中的任何参数。我尝试了https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html中的方法。而且它不起作用
那么,如何在 query.format 中不使用任何参数来执行此操作?
您真的不应该使用 .format
将列值插入到您的 SQL 命令中。搜索 "SQL Injection" 或 "Little Bobby Tables" 以获取更多信息。
相反,您应该使用 ?
参数占位符并将列值作为附加参数提供给 .execute
,如
query = "SELECT col1, col2 FROM tablename WHERE col1 BETWEEN ? AND ?"
myRow = myCursor.execute(query, Start1, End)
对于没有参数值的查询,您只需单独传递 query
字符串
query = "SELECT col1, col2 FROM tablename"
myRow = myCursor.execute(query)