Adding data to Salesforce

Below, I provide a simple Python programme which allows to add data from an external table to Salesforce. The programme uses simple_salesforce as a library. In the first few lines, the necessary libraries are imported.

from simple_salesforce import Salesforce
import pyodbc
import pandas as pd

Then the connection to Salesforce is created.

sf = Salesforce(username='datamigrationuser@pension4you.nl.pensiond2', password='password', security_token='security',domain='test')

Whatever is found in Salesforce is subsequently removed:

queryOutput = sf.query_all("Select Id, code__c, beschrijving__c from SALESFORCEBAK__C")
queryOutputDF = pd.DataFrame(queryOutput['records'])
print('Number of rows in salesforce NW',queryOutputDF.shape)
for i in range(queryOutputDF.shape[0]):
rec = sf.SALESFORCEBAK__C.delete(str(queryOutputDF.iloc[i,1]))
if rec != 204:
print(rec)

Records from an external table are read.

conn = pyodbc.connect('DSN=AzureSQL;UID=tomvanmaanen;PWD=password')
cursor = conn.cursor()
sql = 'SELECT top(100) [code__c],[beschrijving__c] FROM [KONTROLE].[SALESFORCEBAK__C]'
df = pd.read_sql(sql, conn)
cursor.close()

The data are then added to Salesforce.

for i in range(df.shape[0]):
hx1 = str(df.iloc[i,0])
hx2 = df.iloc[i,1]
rec = sf.SALESFORCEBAK__C.create({'code__c' : hx1, 'beschrijving__c' : hx2 })
if rec['success'] != True:
print(rec)

The programme terminates with a check on the number of records that are found in the table.

queryOutput = sf.query_all("Select count(Id) from SALESFORCEBAK__C")
queryOutputDF = pd.DataFrame(queryOutput['records'])
print('Number of rows in salesforce NW ',queryOutputDF.iloc[0,1],' <<<<')

Door tom