La versión 2+ del controlador ODBC de Salesforce le permite procesar por lotes varias declaraciones de inserción SOQL. Este blog le muestra cómo insertar varios registros de Microsoft Access en Salesforce.
Para empezar:
- Instale y obtenga la licencia del controlador ODBC de Salesforce.com en el equipo donde está instalado Microsoft Access.
Antes de poder utilizar el controlador ODBC de Salesforce.com para conectar su aplicación a Salesforce.com, debe configurar una fuente de datos ODBC. Una fuente de datos ODBC almacena los detalles de conexión para la base de datos de destino (p. ej., Salesforce.com) y el controlador ODBC necesario para conectarse (p. ej., el controlador ODBC de Salesforce.com).
Para ejecutar el Administrador ODBC (que usa para crear una fuente de datos), en el cuadro de diálogo Ejecutar de Windows, escriba este comando si está usando una versión de Microsoft Office de 64 bits:
%windir%\system32\odbcad32.exe
–O–
Escriba este comando si está utilizando una versión de Microsoft Office de 32 bits:
%windir%\syswow64\odbcad32.exe
Si no está seguro de si su versión de Microsoft Office es de 32 bits o de 64 bits, inicie una aplicación de Office, p. Microsoft Access y luego busque el proceso de la aplicación en el Administrador de tareas. Si el nombre del proceso es (para Microsoft Access) MSACCESS.EXE *32, Microsoft Office es de 32 bits. Si el nombre del proceso es MSACCESS.EXE, Microsoft Office es de 64 bits.
Para crear una fuente de datos del controlador ODBC de Salesforce.com:
- En el Administrador de ODBC, elija la pestaña DSN del sistema y luego elija Agregar.
- En el cuadro de diálogo Crear nueva fuente de datos, seleccione Easysoft Salesforce ODBC SOQL Driver y luego seleccione Finalizar.
- Complete el cuadro de diálogo Easysoft Salesforce SOQL ODBC Driver DSN Setup:
Configuración Valor DNS SFSOQL Nombre de usuario El nombre de su usuario de Salesforce.com. Por ejemplo, myuser@mydomain.com. Contraseña La contraseña de su usuario de Salesforce.com. Ficha El token de seguridad para su usuario de Salesforce.com, si es necesario. Para averiguar si necesita proporcionar un token de seguridad, elija el botón Probar. Si el intento de conexión falla con un error que contiene
LOGIN_MUST_USE_SECURITY_TOKEN, debe proporcionar uno.Salesforce.com envía por correo electrónico el token de seguridad a la dirección de correo electrónico asociada con su cuenta de usuario de Salesforce.com. Si no ha recibido un token de seguridad, puede regenerarlo. Salesforce.com luego le enviará por correo electrónico el nuevo token de seguridad. Para regenerar su token de seguridad, inicie sesión en Salesforce.com y luego seleccione Configuración en el menú de usuario. Busque "token de seguridad" en el cuadro Búsqueda rápida. Haga clic en Restablecer token de seguridad en la página Restablecer token de seguridad. Cuando reciba el token en su cliente de correo electrónico, cópielo y luego péguelo en el campo Token.
- Utilice el botón Probar para verificar que puede conectarse con éxito a Salesforce.com.
Acceso de Microsoft
- Cree una nueva base de datos de Microsoft Access.
- Cree una tabla llamada Cuenta con estas columnas:
Columna Tipo de datos ID Autonumeración Nombre de cuenta Texto corto Descripción de la propiedad Texto corto Dirección Texto corto Pueblo Texto corto Código postal Texto corto - Ingrese algunos datos de muestra en la tabla. Por ejemplo:
AccName Property Description Address Town PostCode MyCo Head Office 1 MyStreet MyTown AB1 DEF AcmeLtd Workshop 1 MyRoad MyTown AB1 XYZ
- Presione ALT+F11 para iniciar el Editor de Visual Basic.
- Inserte un nuevo módulo y agregue el siguiente código. Hay dos subrutinas y una función auxiliar. Ambas subrutinas insertan los registros de Access en Salesforce de forma masiva. La segunda subrutina muestra cómo usar una instrucción de inserción SOQL parametrizada.
- En el menú Ejecutar, use Ejecutar Sub/UserForm para ejecutar las subrutinas.
Option Compare Database
Sub InsertAccounts()
Dim con As New ADODB.Connection
Dim comm As New ADODB.Command
Dim PrmName As New ADODB.Parameter
Dim PrmAddress As New ADODB.Parameter
Dim PrmTown As New ADODB.Parameter
Dim PrmPostCode As New ADODB.Parameter
Dim PrmDescription As New ADODB.Parameter
Dim RowCount As Long
Dim i As Integer
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim BlockCount As String
Dim isPosted As Boolean
RowCount = 0
' Open the connection to the Easysoft Salesforce SOQL ODBC Driver data source
con.Open "SFSOQL"
comm.ActiveConnection = con
' Set up the initial insert statement using ? for each column I am going to pass in
comm.CommandText = "insert into Account (Name, BillingStreet, BillingCity, BillingPostalCode, Description ) values ( ?, ?, ?, ?, ? )"
' Bind all the columns to the statement
Set PrmName = comm.CreateParameter("P1", adVarWChar, adParamInput, 255, Null)
Set PrmAddress = comm.CreateParameter("P2", adVarWChar, adParamInput, 255, Null)
Set PrmTown = comm.CreateParameter("P3", adVarWChar, adParamInput, 120, Null)
Set PrmPostCode = comm.CreateParameter("P4", adVarWChar, adParamInput, 60, Null)
Set PrmDescription = comm.CreateParameter("P5", adLongVarWChar, adParamInput, 255, Null)
comm.Parameters.Append PrmName
comm.Parameters.Append PrmAddress
comm.Parameters.Append PrmTown
comm.Parameters.Append PrmPostCode
comm.Parameters.Append PrmDescription
' Create a connection to the local database and start working through the rows
Set db = CurrentDb
Set rs = db.OpenRecordset("select * from Account order by Id")
BlockCount = 0
Do While Not rs.EOF
RowCount = RowCount + 1
If BlockCount = 0 Then
' Start a new transaction
con.BeginTrans
isPosted = False
End If
BlockCount = BlockCount + 1
Debug.Print RowCount & " : " & rs.Fields("AccName")
DoEvents
' Prepare to transfer the data to the ODBC driver
PrmName.Value = rs.Fields("AccName")
If Not IsNull(rs.Fields("Address")) Then
PrmAddress.Value = Replace(rs.Fields("Address"), ",", vbCrLf)
Else
PrmAddress.Value = Null
End If
If Not IsNull(rs.Fields("Town")) Then
PrmTown.Value = rs.Fields("Town")
Else
PrmTown.Value = Null
End If
If Not IsNull(rs.Fields("Town")) Then
PrmPostCode.Value = rs.Fields("PostCode")
Else
PrmPostCode.Value = Null
End If
If Not IsNull(rs.Fields("Property Description")) Then
PrmDescription.Value = rs.Fields("Property Description")
Else
PrmDescription.Value = Null
End If
comm.Execute
' When 200 rows have been sent to the driver, commit
If BlockCount = 200 Then
Debug.Print "Block posted"
con.CommitTrans
isPosted = True
BlockCount = 0
End If
' Loop through the block until the end is reached
rs.MoveNext
Loop
rs.Close
db.Close
' Finally, if there are any rows left to commit, send them
If Not isPosted Then con.CommitTrans
con.Close
End Sub
Sub InsertAccountsParameterisedSOQL()
Dim con As New ADODB.Connection
Dim SQL As String
Dim SQLBase As String
Dim BlockCount As Long
Dim isPosted As Boolean
Dim RowCount As Long
Dim i As Integer
Dim db As DAO.Database
Dim rs As DAO.Recordset
RowCount = 0
' Open the connection to the Easysoft Salesforce SOQL ODBC Driver data source
con.Open "SFSOQL"
SQLBase = "insert into Account (Name, BillingStreet, BillingCity, BillingPostalCode, Description ) values ( "
' Create a connection to the local database and start working through the rows
Set db = CurrentDb
Set rs = db.OpenRecordset("select * from Account order by Id")
BlockCount = 0
Do While Not rs.EOF
RowCount = RowCount + 1
If BlockCount = 0 Then
' Start a new transaction
con.BeginTrans
isPosted = False
End If
BlockCount = BlockCount + 1
Debug.Print RowCount & " : " & rs.Fields("AccName")
DoEvents
' Prepare to transfer the data to the ODBC driver
SQL = SQLBase
If IsNull(rs.Fields("AccName")) Then
SQL = SQL & "NULL, "
Else
SQL = SQL & "'" & EscQuotes(rs.Fields("AccName")) & "', "
End If
If IsNull(rs.Fields("Address")) Then
SQL = SQL & "NULL, "
Else
SQL = SQL & "'" & EscQuotes(Replace(rs.Fields("Address"), ",", vbCrLf)) & "', "
End If
If Not IsNull(rs.Fields("Town")) Then
SQL = SQL & "NULL, "
Else
SQL = SQL & "'" & EscQuotes(rs.Fields("Town")) & "', "
End If
If IsNull(rs.Fields("PostCode")) Then
SQL = SQL & "NULL, "
Else
SQL = SQL & "'" & EscQuotes(rs.Fields("PostCode")) & "', "
End If
If IsNull(rs.Fields("Property Description")) Then
SQL = SQL & "NULL) "
Else
SQL = SQL & "'" & EscQuotes(rs.Fields("Property Description")) & "')"
End If
con.Execute SQL
' When 200 rows have been sent to the driver then commit
If BlockCount = 200 Then
Debug.Print "Block posted"
con.CommitTrans
isPosted = True
BlockCount = 0
End If
' Loop through the block until the end is reached
rs.MoveNext
Loop
rs.Close
db.Close
' Finally, if there are any rows left to commit, send them
If Not isPosted Then con.CommitTrans
con.Close
End Sub
Function EscQuotes(inpStr As String) As String
EscQuotes = Replace(inpStr, "'", "''")
End Function