You can connect to Salesforce from Go using Devart ODBC Driver for Salesforce.
Run the following command to install the odbc
package.
go get github.com/alexbrainman/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.
var 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.
var 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.
var connectionString = "DRIVER=Devart ODBC Driver for Salesforce;Authentication=OAuth;Refresh Token=your_refresh_token"
For more information, see DSN-less connections.
The following Go code demonstrates how to connect to Salesforce and fetch data using the ODBC driver.
package main
// Import the database/sql package for data source operations, the fmt package for
// formatted input and output, and the ODBC driver package
import (
"database/sql"
"fmt"
_ "github.com/alexbrainman/odbc"
)
func main() {
// Open a connection to the data source using the DSN
var connectionString = "your_connection_string"
db, err := sql.Open("odbc", connectionString)
if err != nil {
// Handle any errors that occur during the connection
fmt.Println("Connection Failed:", err)
return
}
// Ensure the connection is closed when the function exits
defer db.Close()
// Execute an SQL query to retrieve data from the data source
rows, err := db.Query("SELECT Id, Name FROM Account")
if err != nil {
// Handle any errors that occur during the query execution
fmt.Println("Query Failed:", err)
return
}
// Ensure the rows are closed when the function exits
defer rows.Close()
// Iterate over the result set and process each row
for rows.Next() {
var id, name string
// Scan the columns in the current row into variables
err := rows.Scan(&id, &name)
if err != nil {
// Handle any errors that occur during row scanning
fmt.Println("Row Scan Failed:", err)
return
}
// Print the retrieved data
fmt.Println("ID:", id, "Name:", name)
}
// Check for any errors encountered during iteration
if err = rows.Err(); err != nil {
fmt.Println("Rows Iteration Error:", err)
}
}