如何在查询中安全地参数化pyodbc标识符?

2024-10-05 14:28:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个小工具,可以将数据从SQLServer迁移到Postgres

为了使事情顺利进行,我使用字符串concats快速而肮脏地完成了这项工作,因为我还有很多其他问题要解决,而且当时我不想为SQL而烦恼。但是现在一切都安排好了,我想在SQL部门做一些事情

不安全的快速脏版:

import pyodbc
# this is the bad example DON'T do this
    def getDataFromTable(self,table):
        """
        Gets all data from the specified Table.
        table -- Table name as string
        """
        cursor = self.cursor
        SQL = f"""SELECT * FROM {table}""" ## DON'T do this
        cursor.execute(SQL)
        rows = cursor.fetchall()
        records = []
        for row in rows:
            records.append(list(row))
        return records

这工作得非常好,但是SQL注入正在等待发生

我想构建这样的东西(我省略了未更改的部分):

...
cursor = self.cursor
SQL = f"""SELECT * FROM ?""" # Use parameters insted of string concats
cursor.execute(SQL, table) # pass parameters to the execute method.
rows = cursor.fetchall()
...

这看起来不错,是个保险箱,但也不起作用。弹出以下错误:

pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Die @P1-Tabellenvariable muss deklariert werden. (1087) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Anweisung(en) konnte(n) nicht vorbereitet werden. (8180)')

它是德语的,但大致翻译为:必须声明表变量,不能准备语句

如何将变量传递到execute方法中以安全地放置标识符


Tags: theselfexecutesqlservertablethis事情