先解释一下 传值的由来根据,当然是源码喽
# 下面是 cursor.execute()的源码 重要的是对参数 的说明
'''
If args is a list or tuple, %s can be used as a placeholder in the query.
If args is a dict, %(name)s can be used as a placeholder in the query.
'''
def execute(self, query, args=None):
"""Execute a query.
:param query: Query to execute.
:type query: str
:param args: Parameters used with query. (optional)
:type args: tuple, list or dict
:return: Number of affected rows.
:rtype: int
If args is a list or tuple, %s can be used as a placeholder in the query.
If args is a dict, %(name)s can be used as a placeholder in the query.
"""
下面是举例说明
当使用字典、列表和元组等不同的数据类型向cursor.execute()
方法传递值时,可以通过占位符 %s
来表示参数的位置,并将具体的值作为第二个参数传递给cursor.execute()
方法。以下是具体的示例:
使用字典传递参数:
params_dict = {'name': 'John', 'age': 25}
query = "SELECT * FROM users WHERE name = %(name)s AND age = %(age)s"
cursor.execute(query, params_dict)
使用列表传递参数:
params_list = ['John', 25]
query = "SELECT * FROM users WHERE name = %s AND age = %s"
cursor.execute(query, params_list)
使用元组传递参数:
params_tuple = ('John', 25)
query = "SELECT * FROM users WHERE name = %s AND age = %s"
cursor.execute(query, params_tuple)
在这些示例中,%(name)s
和 %s
是占位符,表示参数的位置。在执行cursor.execute()
方法时,第一个参数是查询语句,第二个参数是具体的参数值。
使用字典传递参数时,可以通过键名来引用参数值,而使用列表和元组传递参数时,参数值的顺序需要与占位符的顺序一致。
注意:在执行查询时,如果查询语句中有多个占位符,需要提供与占位符数量相等的参数值。