Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 使用通配符或ILIKE更新语句的SQLAlchemy_Regex_Sqlalchemy_Sql Like - Fatal编程技术网

Regex 使用通配符或ILIKE更新语句的SQLAlchemy

Regex 使用通配符或ILIKE更新语句的SQLAlchemy,regex,sqlalchemy,sql-like,Regex,Sqlalchemy,Sql Like,我需要在update语句中使用ilike,但尝试时它会返回此错误: InvalidRequestError:无法在Python中计算当前条件。为synchronize_session参数指定“fetch”或False 对于此代码: meta.Session.query(i.mappedClass).filter(getattr(i.mappedClass, j).ilike("%"+userid+"%")).update({j:newUserId}) 我可以用一些类似regexp_的东西来替换

我需要在update语句中使用
ilike
,但尝试时它会返回此错误:

InvalidRequestError:无法在Python中计算当前条件。为synchronize_session参数指定“fetch”或False

对于此代码:

meta.Session.query(i.mappedClass).filter(getattr(i.mappedClass, j).ilike("%"+userid+"%")).update({j:newUserId})
我可以用一些类似regexp_的东西来替换,但这有点过分了。我只想更新以适应不区分大小写和两端的空格。

尝试以下方法:

# test columns
userid = "dUmMy"
j = "name" # name of the column
mappedTable = i.mappedClass.__table__ # assuming use of Declarative. if not, mappedTable is the Table object mapped to i.mappedClass
_stmt = (mappedTable.update().where(getattr(i.mappedClass, j).ilike("%"+ userid +"%")).
            values({getattr(i.mappedClass, j): func.lower(getattr(i.mappedClass, j))})
        )
session.execute(_stmt)
生成SQL:

UPDATE person SET name=lower(person.name) WHERE lower(person.name) LIKE lower(?)
实际上,只需删除
where
子句,即可更新表中的所有记录:

_stmt = mappedTable.update().values({getattr(i.mappedClass, j): func.lower(getattr(i.mappedClass, j))})
session.execute(_stmt)
它生成如下SQL:

UPDATE person SET name=lower(person.name)

好吧,那太令人沮丧了

我发现的简单解决方法是:

for i in model.dataTables:
for j in i.idColumn:
    rows = meta.Session.query(i.mappedClass).filter(getattr(i.mappedClass, j).ilike("%"+userid+"%")).all()
     for row in rows:
         setattr(row, j, newuserid)
meta.Session.commit()

理想情况下,我想远离session.execute,但我会把你在这里给出的东西弄得一团糟,看看我能得到什么。我看不出session.execute()与
查询(…).update()
?有什么不同,因为查询处于循环中,可能会导致打开多个连接时出现问题。。。这样看来,使用
session.execute(…)
或?这不仅仅是一种解决方法,而是一种不同的方法。第一种方法基本上是直接在SQL后端执行
SQLUpdate
语句,而解决方法是将每一行作为模型对象加载到内存中,在内存中进行更新,然后将更改提交到SQL后端。如果这是一种维护类型的操作,我认为第一种方法会更好,特别是如果可以从SQL后端的
userid
计算
newuserid
。我不想在每个循环上都执行该语句。第二种方法更适合我,因为用户不能在更新的中途中断循环。