You can connect to Salesforce from Python using Devart ODBC Driver for Salesforce.
Run the following command to install the pyodbc
library.
pip install pyodbc
An ODBC connection requires a connection string, which can either use a predefined DSN or be specified through connection string parameters (a DSN-less connection).
For information about available parameters, see Connection string parameters.
You can use a connection string with a predefined DSN.
connectionString = "DSN=your_dsn"
If you need credentials other than those used in the DSN, specify them in the connection string to override the DSN values.
connectionString = "DSN=your_dsn;User ID=your_username;Password=your_password"
For information on configuring a DSN on specific operating systems, see instructions for Windows, macOS, or Linux.
You can establish a connection without a DSN by specifying all necessary parameters directly in the connection string.
The following example uses OAuth 2.0 authentication.
connectionString = "DRIVER=Devart ODBC Driver for Salesforce;Authentication=OAuth;Refresh Token=your_refresh_token"
For more information, see DSN-less connections.
The following Python code demonstrates how to connect to Salesforce and fetch data using the ODBC driver.
# Import the pyodbc library for ODBC connections
import pyodbc
# Define an ODBC connection string
connectionString = "your_connection_string"
connection = pyodbc.connect(connectionString)
# Create an object to interact with a data source
cursor = connection.cursor()
# Execute a simple SQL query
query = "SELECT Id, Name FROM Account"
cursor.execute(query)
# Fetch and print the query results
print("Query Results:")
for row in cursor.fetchall():
# Output each tuple of the query results to the console
print(row)
# Close the cursor and the connection
cursor.close()
connection.close()