You can connect to Salesforce from C# using Devart ODBC Driver for Salesforce.
If you’re using .Net Core, add the System.Data.Odbc
NuGet package reference from your IDE, or run the following command to add it from the .NET CLI.
dotnet add package System.Data.Odbc
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.
string 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.
string 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.
string connectionString = "DRIVER=Devart ODBC Driver for Salesforce;Authentication=OAuth;Refresh Token=your_refresh_token";
For more information, see DSN-less connections.
The following C# code demonstrates how to connect to Salesforce and fetch data using the ODBC driver.
using System;
using System.Data;
// Import the namespace required for ODBC connections
using System.Data.Odbc;
class Program
{
static void Main()
{
// Define an ODBC connection string
string connectionString = "your_connection_string";
// Create an object that represents a connection to a data source
OdbcConnection connection = new OdbcConnection(connectionString);
try
{
// Open a connection
connection.Open();
Console.WriteLine("Connection was successfully established!");
// Define an SQL query to be executed
string query = "SELECT Id, Name FROM Account";
// Create an object to execute the query
using (OdbcCommand command = new OdbcCommand(query, connection))
{
// Execute the query and retrieve the results
using (OdbcDataReader reader = command.ExecuteReader())
{
// Read and display the data
Console.WriteLine("Retrieved Accounts:");
while (reader.Read())
{
// Access columns by name or index
Console.WriteLine("Id: " + reader["Id"] + " Name: " + reader["Name"]);
}
}
}
}
catch (Exception ex)
{
// Handle any errors that occur
Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
// Close the connection
if (connection.State == ConnectionState.Open)
{
connection.Close();
Console.WriteLine("Connection closed.");
}
}
}
}