python - 如何通过 pandas 库 sqlalchemy 执行 SQL while 循环。不要关闭这个问题,因为我没有找到任何关于这个的答案
问题描述
我正在尝试通过python执行和sql查询。这是基于我关于如何根据两个数据框拆分列的第一个问题(公司扩展和公司名称的拆分)。由于我发现用python编写代码很困难,所以我使用sql查询通过python进行拆分和执行。我只能执行更新等查询,但是当我尝试使用循环时,既没有得到输出,也没有任何错误。
我的输入:
Original_Input Cleansed_Input
DORO INC ( O/S DORO SAFETY & SECURITY) DORO INC OS DORO SAFETY SECURITY
Iris Diagnostics, a Division of Iris International Inc Iris Diagnostics a Division of Iris
International Inc
GINGI-PAK a division of The Belport Co., Inc. GINGIPAK a division of The Belport Co Inc
我的预期输出:
Original_Input Cleansed_Input
DORO INC ( O/S DORO SAFETY & SECURITY) DORO INC OS DORO SAFETY SECURITY
Iris Diagnostics, a Division of Iris International Inc Iris Diagnostics a Division of Iris
International Inc
GINGI-PAK a division of The Belport Co., Inc. GINGIPAK a division of The Belport Co Inc
Core_Input Type_Input
Iris Diagnostics a Division of Iris International Incorporated
GINGIPAK a division of The Belport Company Incorporated
当我只尝试更新语句时,它工作正常,但随后为拆分提供了优先级,所以我尝试使用 while 循环并通过 python 执行,但它不起作用。它在 sql 中运行良好,但不能通过 python 运行。
在代码中 Tempcompanyname 是我的输入和输出表。Company_Extension 是另一个具有扩展名、缩写和优先级的表。
例如,我的第二张桌子如下。
Name_Extension Company_Type Priority
co llc Company LLC 2
Pvt ltd Private Limited 8
Corp orporation 4
Co inc Company Incorporated 9
这是我的一段代码。
engine.execute('''Declare @priority int = (select max(priority) from [company_Extension])
Declare @p int=1
while @p <= @priority
begin
update A
set A.Type_input = B.Company_Type
from [TempCompanyName]A (nolock), [company_Extension]B where A.Cleansed_Input like
'%'+B.Name_Extension and Priority=@p
update A
set A.Core_Input =replace(A.[Cleansed_Input],B.Name_Extension,'')
from [TempCompanyName]A (nolock), [company_Extension]B where A.Cleansed_Input like
'%'+B.Name_Extension and Priority=@p
set @p=@p+1
end''')
engine.execution_options(autocommit=True)
在此先感谢您的帮助。
解决方案
推荐阅读
- typescript - 通过 Typescript / VS Code 导入建议
- php - 下拉列表,当数据库中没有数据时无法手动输入
- postgresql - 唯一约束失败的 PostgreSQL 插入
- apache-kafka - Kafka:防止删除重新处理的过去事件
- properties - 将 SQLAlchemy hybrid_property 与原生属性构造相结合
- javascript - Angular 6 - 无法在自定义 HTML 标签下创建 Angular 组件
- json - Laravel 使用 JSON 生成表单
- java - 使用 Apache POI 拆分 pptx 幻灯片
- java - Java代码不打印excel文件中的所有行
- apache-spark-sql - Spark 1.6 - 使用数据帧失败的 avro 文件覆盖目录