Raw SQL Queries

Hello

While editing my custom queries of the remote database according to the document, I encountered the following error.

pyodbc.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'TOPLAM_SATIS_@P1'. (208) (SQLExecDirectW)")

Query:

cursor.execute("SELECT AY, TOPLAM FROM TOPLAM_SATIS_%s WHERE STOCKREF = %s", [year, stock_ref])

In the document, the parameters are specified as follows cursor.execute(sql, [params])

Where did i go wrong?

The parameters don’t perform string interpolation. It’s not a direct substitution of text into the SQL statement. The SQL statement being prepared is created using parameters, hence the @P1 in the table name reference.

Basically, if you want something interpolated into the SQL other than parameters for things like a where clause, you need to do it yourself.

(Note: Doing this creates an SQL injection vulnerability. Ensure you validate the data appropriately.)

According to the documentation, Django does not allow the “?” sign.

In this case, what should we do to protect ourselves as much as possible from the SQL injection vulnerability?

Yes, but not relevant here. You’re trying to modify the SQL statement itself, not pass parameters to the query. It’s the string containing that statement that you need to modify for what you’re trying to do. (Alter the table name being queried.)

In this specific case, where you want to change the table name, check the value being used to alter that name to ensure it’s an approved value.

You don’t show where/how you’re using this execute statement, so I can’t determine from the information provided what the degree of risk is here. This may be a case where the processing around this statement already mitigates the vulnerability, in which case there’s nothing to worry about.
On the other hand, if this is a value being submitted from a browser, then you really need to make sure it’s clean.

Nothing comes from the user.

Users can only see the data associated with them

In this case, i guess don’t have to worry too much about SQL Injection