将多个字符串变量传递给 python3 中的查询字符串的最佳方法是什么
What is the best way to pass multiple string variables to a query string in python3
我需要创建一个基于两个字符串参数的动态查询:
description = "This is the description"
comment = "This is the comment"
query = "insert into case(desc, comm) value(description, comment)"
注意:
单引号和双引号在描述和评论.
如何使用格式化的 %s 生成查询字符串?
非常感谢。
更新:
感谢Green Cloak Guy(his/her回答有未成年人待更正),正确查询为:
查询=f"insert into case(description, comment) value(\'{description}\', \'{comment}\')"
使用 f 弦。
query = f"insert into case({description}, {comment}) value({description}, {comment})"
不要使用任何类型的字符串格式来进行实际的数据库查询 - 这会导致您遇到 SQL 注入问题。请改用数据库库,它可以正确清理数据。
但是如果您需要做的只是将一些变量解析为字符串,这比其他语言倾向于使用的 %
格式更灵活(技术上在 python 中仍然可用)通过 "some_string %s %s %s" % (str1, str2, str3)"
)
我需要创建一个基于两个字符串参数的动态查询:
description = "This is the description"
comment = "This is the comment"
query = "insert into case(desc, comm) value(description, comment)"
注意: 单引号和双引号在描述和评论.
如何使用格式化的 %s 生成查询字符串?
非常感谢。
更新:
感谢Green Cloak Guy(his/her回答有未成年人待更正),正确查询为:
查询=f"insert into case(description, comment) value(\'{description}\', \'{comment}\')"
使用 f 弦。
query = f"insert into case({description}, {comment}) value({description}, {comment})"
不要使用任何类型的字符串格式来进行实际的数据库查询 - 这会导致您遇到 SQL 注入问题。请改用数据库库,它可以正确清理数据。
但是如果您需要做的只是将一些变量解析为字符串,这比其他语言倾向于使用的 %
格式更灵活(技术上在 python 中仍然可用)通过 "some_string %s %s %s" % (str1, str2, str3)"
)