使用 Python 函数将字符串传递给 pymysql 游标
Passing strings to pymysql cursor using Python function
我正在编写一个脚本,该脚本将使用 pymysql 和一个简单的 SELECT 语句从数据库中提取数据。我要多次 运行 这个语句,所以我希望通过将它放在一个函数中并将列名、table 名称、where 子句和值作为参数传递给函数来简化事情.
def retrieve_value_from_db(connection,column_name,table_name,where_clause,where_value):
with connection:
with connection.cursor() as cursor:
sql = "SELECT %s FROM %s WHERE %s=%s"
logging.debug(cursor.mogrify(sql,(column_name,table_name,where_clause,where_value)))
cursor.execute(sql,(column_name,table_name,where_clause,where_value))
result = cursor.fetchone()
connection.commit()
return result
但是调用下面的函数returns出现如下错误
retrieve_value_from_db(connection,"last_name","mother_table","id","S50000")
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''mother_table' WHERE 'id'='S50000'' at line 1")
Cursor.execute 似乎在读取字符串的引号部分,这是导致编程错误的原因。那么如何将字符串参数传递给 cursor.execute 可以读取的函数呢?我想做的事有可能吗?提前致谢。
也许令人惊讶的是,您不应该让数据库替换处理 table 名称和列名称。它试图像引用字段一样引用它们,这是错误的。
sql = "SELECT %s FROM %s WHERE %s=%%s" % (column_name,table_name,where_clause)
...
cursor.execute(sql, (where_value,))
我正在编写一个脚本,该脚本将使用 pymysql 和一个简单的 SELECT 语句从数据库中提取数据。我要多次 运行 这个语句,所以我希望通过将它放在一个函数中并将列名、table 名称、where 子句和值作为参数传递给函数来简化事情.
def retrieve_value_from_db(connection,column_name,table_name,where_clause,where_value):
with connection:
with connection.cursor() as cursor:
sql = "SELECT %s FROM %s WHERE %s=%s"
logging.debug(cursor.mogrify(sql,(column_name,table_name,where_clause,where_value)))
cursor.execute(sql,(column_name,table_name,where_clause,where_value))
result = cursor.fetchone()
connection.commit()
return result
但是调用下面的函数returns出现如下错误
retrieve_value_from_db(connection,"last_name","mother_table","id","S50000")
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''mother_table' WHERE 'id'='S50000'' at line 1")
Cursor.execute 似乎在读取字符串的引号部分,这是导致编程错误的原因。那么如何将字符串参数传递给 cursor.execute 可以读取的函数呢?我想做的事有可能吗?提前致谢。
也许令人惊讶的是,您不应该让数据库替换处理 table 名称和列名称。它试图像引用字段一样引用它们,这是错误的。
sql = "SELECT %s FROM %s WHERE %s=%%s" % (column_name,table_name,where_clause)
...
cursor.execute(sql, (where_value,))