jeudi 28 février 2019

Check if records exist with Python

I'm going from SQL to python and I'm still kind of confused. It's the following here in my code I want to know if the select values ​​of the result variable exist in the select of the sell variable, and if they exist do nothing, and if they do not load the data. In sql I used If exists, I do not know what the equivalent in python is. Thank you very much in advance.

Example I am bringing a record from a sql table and loading into another mysql table, then in case you already have those records in the mysql table I want you to print on the screen: you do not have new records, and in case you have a record you have not yet are in the table of Mysql I want to load those logs.

Note: I set the data in the dataframe and then load it in mysql

import pymysql.cursors
import pyodbc
import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.types import Integer, VARCHAR, DECIMAL, DATETIME 
from datetime import date


connection = pyodbc.connect("DSN=SQLServer")  #autocommit=True

try:
    with connection.cursor() as cursor:
        result = "SELECT * FROM dw.dbo.vW_sale"
        df = pd.read_sql_query(result,connection,index_col=None,coerce_float=True, parse_dates= 'DataBaseContrato')
        cursor.execute(result)
        table = cursor.fetchall()
        print(table)             

finally:
    connection.close()

#Conexão Mysql
cnx = create_engine('mysql+pymysql://test:test@test/dw')
cnxmysql = pymysql.connect(host='test',
                             user='test',
                             password='test',
                             db='dw')
try:
    with cnxmysql.cursor() as cursor2:
        sale = "SELECT * FROM ft_sale_test"
        cursor2.execute(venda)
        sale = cursor2.fetchall()
        print(sale)
finally:
    cnxmysql.close()

df.to_sql(con=cnx, name= 'ft_sale_test',if_exists= 'replace', index= False)
print('Loading data')

Aucun commentaire:

Enregistrer un commentaire