我正在尝试删除 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/