如何在 Python 中替换 SQL 连接中的字符串

how to substitute string in SQL connection in Python

我有一个变量(交换),我循环遍历代码中的值以更改每次交换的输出文件的路径。当我还尝试在 SQL 块中使用此字符串替换时,它无法理解。 有人可以建议出什么问题了吗?这是我得到的错误

pandas.io.sql.DatabaseError: Execution failed on sql '
    f'SELECT [Ticker], [Date], [Open], [High], [Low], [Close], [Volume] FROM olaptraderv3.dbo.{ex} order by Ticker'
    ': ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Could not find stored procedure 'f'. (2812) (SQLExecDirectW)")

代码的相关部分如下:

import pandas as pd

pd.options.mode.chained_assignment = None  # default='warn'
import pyodbc
import talib
import os
from talib import  (AD,ADOSC,WILLR)

exchanges = ["BATS","US","V"]

for ex in exchanges:
path = f'H:\EOD_DATA_RECENT\INDICATORS\FROM-SQL-SOURCE\{ex}\'

DB_READ = {'servername': 'XYZ\XYZ',
  'database': 'olaptraderv3'}

conn = pyodbc.connect('DRIVER={SQL Server};SERVER=' + DB_READ['servername'] + ';DATABASE=' +  DB_READ['database'] + ';Trusted_Connection=yes')

sql = """
f'SELECT [Ticker], [Date], [Open], [High], [Low], [Close], [Volume] FROM olaptraderv3.dbo.{ex} order by Ticker'
"""
df = pd.read_sql(sql, conn)

您需要在字符串外使用 'f' 格式。

sql = f"""
'SELECT [Ticker], [Date], [Open], [High], [Low], [Close], [Volume] FROM olaptraderv3.dbo.{ex} order by Ticker'
"""

我非常不鼓励用 SQL 做字符串 formatting/substitution,因为它没有经过清理,可能会被滥用。