Python SQLAlchemy查询以查找和替换列中存在的子字符串
我试图在SqlAlchemy中编写一个查询,以查找一个子字符串,如果它存在于列中,则用另一个字符串替换它。实现这一目标的最佳方式是什么 我正在尝试使用Python SQLAlchemy查询以查找和替换列中存在的子字符串,python,postgresql,sqlalchemy,Python,Postgresql,Sqlalchemy,我试图在SqlAlchemy中编写一个查询,以查找一个子字符串,如果它存在于列中,则用另一个字符串替换它。实现这一目标的最佳方式是什么 我正在尝试使用regexp\u replace。我想不出如何使用它。到目前为止,我尝试的是: regexp_statement = table.select(sqlalchemy.func.regexp_replace(*regexp)) 但这会转化为错误的sql查询从regexp\u replace(字符串、搜索字符串、替换字符串)所在的表名称中选择* 如何
regexp\u replace
。我想不出如何使用它。到目前为止,我尝试的是:
regexp_statement = table.select(sqlalchemy.func.regexp_replace(*regexp))
但这会转化为错误的sql查询<代码>从regexp\u replace(字符串、搜索字符串、替换字符串)所在的表名称中选择*
如何在sqlalchemy中正确使用regexp\u replace?更新 您需要使用
更新
,而不是选择
。尝试使用以下方法:
replace_func = sqlalchemy.func.regexp_replace(
table.c.column,
your_string_to_replace,
your_string_to_replace_with
)
table.update(values={table.c.column: replace_func})
旧的
您可以使用原始sql进行以下操作:
sql_expr = (
"update {table} set {field} = " +
"replace({field}, {str_to_repl}, {str_to_repl_with});"
).format(
table=your_table_name,
field=your_field_name,
str_to_repl=your_string_to_replace,
str_to_repl_with=your_string_to_replace_with,
)
session.execute(sql_expr)
session.commit()
更新 您需要使用
更新
,而不是选择
。尝试使用以下方法:
replace_func = sqlalchemy.func.regexp_replace(
table.c.column,
your_string_to_replace,
your_string_to_replace_with
)
table.update(values={table.c.column: replace_func})
旧的
您可以使用原始sql进行以下操作:
sql_expr = (
"update {table} set {field} = " +
"replace({field}, {str_to_repl}, {str_to_repl_with});"
).format(
table=your_table_name,
field=your_field_name,
str_to_repl=your_string_to_replace,
str_to_repl_with=your_string_to_replace_with,
)
session.execute(sql_expr)
session.commit()
但是我必须在sqlalchemy中执行它。-1用于字符串格式化SQL查询,而不是使用正确的和绑定的参数。但是我必须在sqlalchemy中执行它。-1用于字符串格式化SQL查询,而不是使用正确的和绑定的参数。但是我必须在sqlalchemy中执行它。-1用于字符串格式化SQL查询,而不是使用正确的和绑定的参数。