我有一个与python的连接,它将SQL Server数据库中的记录带到MySQL数据库中。我对它进行了编程,使脚本每小时运行一次,如果有任何更改,记录将直接替换为“如果存在替换”。
问题是,现在我必须将MySQL数据库中的一些记录与另一个表链接起来。当运行脚本时,它们会被删除或复制。我也遇到过这样的情况:如果在源SQL数据库中删除了一条记录,它就不会删除。它在MySQL中被删除。我试过使用触发器,但找不到方法。
这是我尝试使用的最后一个代码(我没有放入连接数据)
columns_to_update = ['Fecha', 'Vencimiento', 'Saldo', 'Comprobante', 'Corredor', 'Grupo', 'Nombre', 'Telefono', 'Email', 'Mora', 'Rango_venc']
# Obtener los datos existentes de la tabla
# Obtener los datos existentes de la tabla
existing_data_query = "SELECT * FROM cobranzas_cliente"
existing_data = pd.read_sql(existing_data_query, engine)
for table_name, table_content in tables_content.items():
# Reemplazar los valores "NULL" por None
table_content = table_content.fillna(0)
# Reemplazar los valores en blanco o espacios en blanco por 0
table_content = table_content.replace(['', ' '], 0)
# Crear una nueva tabla temporal con las filas únicas
table_content_unique = table_content.drop_duplicates(subset=columns_to_update)
# Agregar nuevos registros y actualizar registros existentes
for row in table_content_unique.itertuples(index=False):
# Verificar si el registro ya existe antes de insertar
comprobante_value = getattr(row, "Comprobante")
comprobante_query = f"SELECT * FROM cobranzas_cliente WHERE Comprobante = '{comprobante_value}'"
existing_comprobante = pd.read_sql(comprobante_query, engine)
if existing_comprobante.empty:
# Insertar un nuevo registro
insert_values = [f"'{getattr(row, column)}'" for column in row._fields]
insert_query = f"INSERT INTO cobranzas_cliente ({', '.join(row._fields)}) VALUES ({', '.join(insert_values)})"
engine.execute(insert_query)
else:
# Actualizar el registro existente
update_values = [f"{column} = '{getattr(row, column)}'" for column in columns_to_update]
update_query = f"UPDATE cobranzas_cliente SET {', '.join(update_values)} WHERE Comprobante = '{comprobante_value}'"
engine.execute(update_query)
# Eliminar registros que ya no están en la tabla tables_content
delete_rows = []
for existing_row in existing_data.itertuples(index=False):
condition_values = [f"{column} = '{getattr(existing_row, column)}'" for column in columns_to_update]
condition_query = f"SELECT * FROM cobranzas_cliente WHERE {' AND '.join(condition_values)}"
matching_row = pd.read_sql(condition_query, engine)
if matching_row.empty:
delete_rows.append(existing_row)
if delete_rows:
for row in delete_rows:
condition_values = [f"{column} = '{getattr(row, column)}'" for column in columns_to_update]
delete_query = f"DELETE FROM cobranzas_cliente WHERE {' AND '.join(condition_values)}"
engine.execute(delete_query)