python - 删除列值与 Pandas Dataframe 列值匹配的 SQL 表行

标签 python sqlalchemy

我正在尝试删除 SQL 表中的行,这些行在我的 pandas 数据框中具有匹配的列值。这是我到目前为止的代码。由于某种原因,它仅适用于某些数据。我不断收到下面列出的错误。执行此操作的最佳方法是什么?

import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy import update
from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy import Table
from sqlalchemy import select
from sqlalchemy import or_
from sqlalchemy import and_

    engine = create_engine(cnxn_str)
    meta = sqlalchemy.MetaData()
    # Map the Inventory table in your database to a SQLAlchemy object
    inventory = sqlalchemy.Table(table_name, meta, autoload=True, autoload_with=engine)
    #make the condition
    cond = inventory.c['column_name'].in_(df['column_name'])
    # Define and execute the DELETE
    delete = inventory.delete().where(cond)
    with engine.connect() as conn:
        conn.execute(delete)

DBAPIError: (pyodbc.Error) ('07002', '[07002] [Microsoft][ODBC Driver 13 for SQL Server]COUNT field incorrect or syntax error (0) (SQLExecDirectW)') [SQL: 'DELETE FROM [table_name] WHERE [table_name].[column_name] IN (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,

最佳答案

这篇文章有点老了。尽管如此,我还是会分享我的解决方案,以便对其他人有所帮助。

我遇到了类似的问题并最终创建了以下函数:

def execute_query(query: str, is_fw=False, conexion_ar=con_db_AR, conexion_fw="con_db_FW"):
"""

Parameters:
    query(str): Text with the query
    conexion_ar: Conexion to Redshift
    conexion_fw: Conexion to the framework
"""
if is_fw:
    conexion = conexion_fw
else:
    conexion = conexion_ar

conexion.execute(f"{query}; commit;")

希望对你有帮助;D

关于python - 删除列值与 Pandas Dataframe 列值匹配的 SQL 表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58018877/

相关文章:

python - Django 是否有像 South 这样的 SQLAlchemy 自动迁移工具?

python - Flask:为什么 app.route() 装饰器应该总是在最外面?

使用 Ajax 的 Javascript POST 到 Django 不起作用

python - 无一异常(exception)地获取 python 回溯

python - 如何在python中使用多处理将df的内容写入csv文件

python - SQLAlchemy 和 django,准备好生产了吗?

python - sqlalchemy经典映射关系问题

python - 无法更改系统默认的 SQLite 二进制文件

python - 如何在 python flask sqlalchemy marshmallow 应用程序中将一个属性对象数组渲染为平面数组?

python - 运行后在解释器中访问脚本的变量和函数