Inserting Records with SQLForce
SQLForce has two techniques for inserting records into Salesforce:
- A standard ANSI INSERT statement.
- An insert() method — always use this approach when inserting a lot of records.
With SQLForce you do not need to worry about the Salesforce “200 records per insert call” restriction. SQLForce will batch records for you automatically.
ANSI INSERT Statement
SQLForce supports an INSERT statement of the form:
- INSERT INTO tableName (column [,column]*) VALUES(v1 [,v2]*) [, (v1, [v2]*)]*
For example:
- INSERT INTO Account(name) VALUES(‘University of Tokyo’)
- INSERT INTO Contact(firstName, lastName) VALUES(‘Fred’, ‘Flintstone’), (‘Barney’, ‘Rubble’)
The SQLForce Session.runCommands() method is used to execute these queries, for example:
session = SQLForce.Session(‘MyProfile’)
session.runCommands(“INSERT INTO Account(name) VALUES(‘University of Tokyo’)”)
nInserted = session.getenv(‘ROW_COUNT’)
The session.getenv() call retrieves a SQLForce variable that holds the count of rows affected by the most recent INSERT/UPDATE/DELETE statement.
Session.insert() Method
The Session.insert() method is generally a simpler approach for inserting records using Python:
- session.insert(‘TableName’, <list of columns to insert>, <list of values for each record to insert>)
For example:
- session.insert(‘Account’, [‘Name’, ‘Industry’], [[‘BigTech’, ‘Commercial’], [‘Kaplan’, ‘Academic’]])
In this example:
- The first argument, ‘Account’, is the name of the table into which the records will be inserted.
- The second argument is a list of column names to insert. The column order must match the order of data values in the next parameter.
- The third argument is a list of lists where each sub-list contains the values for a new record.
This method returns a list of the new Salesforce Ids, in the same order as the data in the call to session.insert().