I currently have this query:
JavaScript
x
10
10
1
for table_name in bmds_stage_tables:
2
get_updated_tables = conn.execute(
3
f"""
4
DECLARE @csId INT = ?
5
SELECT * FROM bmds_stage.{table_name}
6
WHERE ChangeSetId = @csId
7
""",
8
change_set_ids
9
).fetchall()
10
That I changed to use bindparams
:
JavaScript
1
10
10
1
query_updated_tables = text(
2
"""
3
SELECT * FROM bmds_stage.:table_name
4
WHERE ChangeSetId in :csId
5
"""
6
).bindparams(
7
bindparam("table_name"),
8
bindparam("csId", expanding=True),
9
)
10
So before, I was able to make the query per table in the bmds_stage_table
list and change_set_ids was just 1 int
But now change_set_ids
is a list of int
s.
So now, for each change_set_id
I want to iterate through all the tables in the bmds_stage_table
list
With the change I had to adjust how I execute the query:
JavaScript
1
3
1
for table_name in bmds_stage_tables:
2
get_updated_tables = conn.execute(query_updated_tables, {"table_name":table_name, "csId":change_set_id}).fetchall()
3
But I get this error:
JavaScript
1
7
1
sqlalchemy.exc.ProgrammingError: (pyodbc.ProgrammingError) ('42000', "[42000] [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near '@P1'. (102) (SQLExecDirectW)")
2
[SQL:
3
SELECT * FROM bmds_stage.?
4
WHERE ChangeSetId in (?)
5
]
6
[parameters: ('PM_Category', 1045)]
7
I would greatly appreciate any help!
Advertisement
Answer
Consider formatting the table name to raw SQL since identifiers cannot be parameterized and bind_params
for literal values:
JavaScript
1
16
16
1
for table_name in bmds_stage_tables:
2
query_updated_tables = text(
3
f"""SELECT * FROM bmds_stage.{table_name}
4
WHERE ChangeSetId in :csId
5
"""
6
).bindparams(
7
bindparam("csId", expanding=True)
8
)
9
10
params = {"csId": change_set_id}
11
get_updated_tables = (
12
conn.execute(
13
query_updated_tables, params
14
).fetchall()
15
)
16
Possibly, too, consider the functional form of sqlalchemy:
JavaScript
1
24
24
1
from sqlalchemy.schema import Table
2
from sqlachemy import select, column, bindparam
3
4
for table_name in bmds_stage_tables:
5
query_updated_tables = (
6
select(
7
Table(
8
table_name,
9
schema = "bmds_stage"
10
)
11
).where(
12
column("ChangeSetId").in_(
13
bindparam("csId", expand=True)
14
)
15
)
16
)
17
18
params = {"csId": change_set_id}
19
get_updated_tables = (
20
conn.execute(
21
query_updated_tables, params
22
).fetchall()
23
)
24