Dynamics 365 CE/CRM

Building the JDBC URL

After installing the license, access the connection management page by executing the command "java -jar kingswaysoft.jdbc.jar". Enter the necessary details, and the program will automatically generate the JDBC connection URL. Users can click Test Connection to test the generated URL and Copy to Clipboard to copy the connection string for use within the application where the JDBC driver is being used.

Note: If a license is not installed, you can still use the connection manager to generate a JDBC URL, but the 'Test Connection' feature will be disabled.

connectionmanage

There are two ways to connect to Dynamics CRM:

Active Directory

Enter User Name, Password, Domain, and Server URL to establish a connection.

OAuth

Client Credentials

Enter Authentication Server, Server URL, and the Client ID, Client Secret, and Tenant configured in the portal to establish a connection.

Authorization Code

A saved token file and token password can be used to establish a connection. If you wish to generate a new token file, click Generate Token File to go through the token generation process, save the token file locally, and use the set token password to connect.

Certificate

Users can choose to use a saved certificate file and certificate password to establish a connection. Alternatively, they can click "Generate New Certificate" to go through the certificate process, generate a keystore, save it locally, and use the set certificate password to connect. (Note: The certificate file only supports the PFX format. For newly generated certificates, the simultaneously generated PEM file needs to be configured in the portal.)

Using the JDBC Driver

Explore detailed examples in this section that demonstrate the application of JDBC classes such as Connection, Statement, and ResultSet to effectively manage interactions with Dynamics data. This section covers the use of regular statements and prepared statements for executing complex or frequently executed queries.

Executing Statements

Once you've connected from your code (see Connecting with DriverManager and Connecting with DataSource), you can execute SQL statements using the Statement class. Refer to the Executing Prepared Statements section for information on how to execute parameterized statements.

SELECT

Use the Statement class's generic execute method or the executeQuery method to execute SQL statements that return data. To retrieve the results of a query, you would then call the getResultSet method of the Statement.

Statement statement = connection.createStatement();	
String sql = "SELECT contactid, firstname, lastname FROM contact WHERE lastname = 'test'";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
    for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
      LOGGER.info(resultSet.getMetaData().getColumnLabel(i) + "=" + resultSet.getString(i));
    }
}

INSERT

Use either the generic execute method or the executeUpdate method of the Statement class to execute an INSERT operation.

The results of SQL queries are saved in a ResultSet. You can retrieve the ResultSet after execution to view the inserted data's ID, exceptions raised during execution, and details of the affected data.

String sql = "INSERT INTO contact (firstname, lastname) VALUES ('test first', 'test last')";
try {
    Statement statement = connection.createStatement();				
    statement.executeUpdate(sql);
    LOGGER.info(statement.getResultSet().toString());
} catch (SQLException e) {
    LOGGER.error(e);
}	
id,errorcode,errormessage,processdata
ba9374d2-9508-ef11-9f89-000d3af33381,null,null,{"firstname":"test first","lastname":"test last"}

UPDATE

Use either the generic execute method or the executeUpdate method of the Statement class to execute an UPDATE operation.

The MatchHandling property will effect how UPDATE operations perform when multiple records are found that match the search criteria.

The results of SQL queries are saved in a ResultSet. You can retrieve the ResultSet after execution to view the updated data's ID, exceptions raised during execution, and details of the affected data.

String sql = "UPDATE Contact SET Firstname = 'test first1' WHERE lastname = 'test last'"try {	
    Statement statement = connection.createStatement();			
    statement.executeUpdate(sql);
    LOGGER.info(statement.getResultSet().toString());
} catch (SQLException e) {
    LOGGER.error(e);
}	
id,errorcode,errormessage,processdata
50d691b8-bf08-ef11-9f89-000d3af33381,null,null,{"firstname":"test first1"}

DELETE

Use either the generic execute method or the executeUpdate method of the Statement class to execute a DELETE operation.

The MatchHandling property will effect how DELETE operations perform when multiple records are found that match the search criteria.

The results of SQL queries are saved in a ResultSet. You can retrieve the ResultSet after execution to view the deleted data's ID, exceptions raised during execution, and details of the affected data.

String sql = "DELETE FROM Contact WHERE lastname = 'test last'";
try {	
    Statement statement = connection.createStatement();			
    statement.executeUpdate(sql);
    LOGGER.info(statement.getResultSet().toString());
} catch (SQLException e) {
    LOGGER.error(e);
}	
id,errorcode,errormessage,processdata
50d691b8-bf08-ef11-9f89-000d3af33381,null,null,null

UPSERT

Using the UPSERT operation, you can either insert or update an existing record in one call. If the specified alternate key isn't matched, a new object record will be created.

If the specified key is matched, the action taken will depend on if there were multiple matches or not.

  • If the key is matched once, the existing object record is updated.
  • If the key is matched multiple times, an error is generated and the object record is not inserted or updated.

The Upsert SQL statement must end with 'ON DUPLICATE KEY UPDATE UPSERTFIELDS = key', where 'key' refers to the field specified by the user as the upsert key.

The results of SQL queries are saved in a ResultSet. You can retrieve the ResultSet after execution to view the upserted data's ID, exceptions raised during execution, and details of the affected data.

String sql = "UPSERT INTO contact (firstname, lastname, emailaddress1, creditlimit) VALUES 
    ('testFirst1', 'testLast1', '[email protected]', 100), 
    ('testFirst2', 'testLast2', '[email protected]', 200) 
    ON DUPLICATE KEY UPDATE UPSERTFIELDS = (firstname, lastname, emailaddress1)";

try {
    Statement statement = connection.createStatement();				
    statement.executeUpdate(sql);
    LOGGER.info(statement.getResultSet().toString());
} catch (SQLException e) {
    LOGGER.error(e);
}	
id,errorcode,errormessage,processdata,isNew
32f740a8-a508-ef11-9f89-000d3af33381,null,null,{"creditlimit":100.00},true
34f740a8-a508-ef11-9f89-000d3af33381,null,null,{"creditlimit":200.00},true

Executing Prepared Statements

Using a PreparedStatement can improve performance when you need to execute a SQL statement multiple times with different parameters. Unlike a Statement object, a PreparedStatement object is provided with a SQL statement when it is created, which can then be executed with different values each time. This special type of statement is derived from the more general class, Statement.

Below are the steps outlining how to execute a prepared statement:

  1. Create a PreparedStatement: Use the prepareStatement method of the Connection class to instantiate a PreparedStatement. Refer to Connecting with DriverManager or Connecting with DataSource for information related to establishing connections.
  2. Set Parameters: Declare parameters by calling the corresponding setter method of the PreparedStatement. Note: The parameter indices start at 1.
  3. Execute the Statement: Use the generic execute or executeUpdate method of the PreparedStatement.
  4. Retrieve Results: Call the getResultSet method of the Prepared Statement to obtain the query results, which will be returned as a ResultSet.
  5. Iterate Over the Result Set: Use the next method of the ResultSet to iterate through the results. To obtain column information, utilize the ResultSetMetaData class. Instantiate a ResultSetMetaData object by calling the getMetaData method of the ResultSet.

SELECT

Use the Statement class's generic execute method or the executeQuery method to execute SQL statements that return data.

The results of SQL queries are saved in a ResultSet. You can retrieve the ResultSet after execution to view the retrieved data.

String sql = "SELECT * FROM contact WHERE first = ?";
try {
    PreparedStatement ps = connection.prepareStatement(sql);
    ps.setString(1, "test first");
    ps.execute(sql);
    while (ps.getResultSet().next()) {
        for (int i = 1; i <= ps.getResultSet().getMetaData().getColumnCount(); i++) {
            LOGGER.info(ps.getResultSet().getMetaData().getColumnLabel(i) + "=" 
            + ps.getResultSet().getString(i));
        }
    }
} catch (SQLException e) {
    LOGGER.error(e);
}

INSERT

Use either the generic execute method or the executeUpdate method of the Statement class to execute an INSERT operation.

The results of SQL queries are saved in a ResultSet. Users can retrieve the ResultSet after execution to view the ID of inserted data, exceptions raised during execution, and the data affected by the insertion.

String sql = "INSERT INTO Contact (Firstname, Lastname) VALUES (?, ?)";
try {	
    PreparedStatement ps = connection.prepareStatement(sql);		
    ps.setString(1, "first");
    ps.setString(2, "last");
    ps.executeUpdate();
    LOGGER.info(ps.getResultSet().toString());
} catch (SQLException e) {
    LOGGER.error(e);
}	
id,errorcode,errormessage,processdata
89f1fde0-c008-ef11-9f89-000d3af33381,null,null,{"firstname":"first","lastname":"last"}

UPDATE

Use either the generic execute method or the executeUpdate method of the Statement class to execute an UPDATE operation.

The MatchHandling property will effect how UPDATE operations perform when multiple records are found that match the search criteria.

The results of SQL queries are saved in a ResultSet. Users can retrieve the ResultSet after execution to view the ID of updated data, exceptions raised during execution, and the data affected by the update.

String sql = "UPDATE Contact SET Firstname = ? WHERE lastname = ?";
try {	
    PreparedStatement ps = connection.prepareStatement(sql);
    ps.setString(1, "first1");
    ps.setString(2, "last");
    ps.executeUpdate();
    LOGGER.info(ps.getResultSet().toString());
} catch (SQLException e) {
    LOGGER.error(e);
}	
id,errorcode,errormessage,processdata
89f1fde0-c008-ef11-9f89-000d3af33381,null,null,{"firstname":"first1"}

DELETE

Use either the generic execute method or the executeUpdate method of the Statement class to execute a DELETE operation.

The MatchHandling property will effect how DELETE operations perform when multiple records are found that match the search criteria.

The results of SQL queries are saved in a ResultSet. You can retrieve the ResultSet after execution to view the deleted data's ID, exceptions raised during execution, and details of the affected data.

String sql = "DELETE FROM Contact WHERE lastname = ?";
try {	
    PreparedStatement ps = connection.prepareStatement(sql);
    ps.setString(1, "last");
    ps.executeUpdate();
    LOGGER.info(ps.getResultSet().toString());
} catch (SQLException e) {
    LOGGER.error(e);
}	
id,errorcode,errormessage,processdata
89f1fde0-c008-ef11-9f89-000d3af33381,null,null,null

UPSERT

Using the UPSERT operation, you can either insert or update an existing record in one call. If the specified alternate key isn't matched, a new object record will be created.

If the specified key is matched, the action taken will depend on if there were multiple matches or not.

  • If the key is matched once, the existing object record is updated.
  • If the key is matched multiple times, an error is generated and the object record is not inserted or updated.

The Upsert SQL statement must end with 'ON DUPLICATE KEY UPDATE UPSERTFIELDS = key', where 'key' refers to the field specified by the user as the upsert key.

The results of SQL queries are saved in a ResultSet. You can retrieve the ResultSet after execution to view the upserted data's ID, exceptions raised during execution, and details of the affected data.

String sql = "UPSERT INTO account (name, accountnumber) VALUES (?, ?) ON DUPLICATE KEY UPDATE UPSERTFIELDS = (accountnumber)";
try {
    PreparedStatement ps = connection.prepareStatement(sql);    
    ps.setString(1, "test");
    ps.setString(2, "TEST");
    ps.executeUpdate();
    LOGGER.info(ps.getResultSet().toString());
} catch (SQLException e) {
    LOGGER.error(e);
}	
id,errorcode,errormessage,processdata,isNew
947dcce5-95f0-ef11-be20-7ced8d058096,null,null,{"name":"test"},false

Metadata Discovery

This section provides examples on how to retrieve table and column metadata using the getTables, getColumns, and getPrimaryKeys methods from the DatabaseMetaData interface. These are essential for discovering database structures.

Tables

The getTables method from the DatabaseMetaData interface can be used to retrieve a list of tables.

Class.forName("com.kingswaysoft.jdbc.Drivers");

Properties connectionProps = new Properties();
connectionProps.put("user", "username");
connectionProps.put("password", "password");

Connection connection = DriverManager.getConnection("jdbc:ServiceName=DyanmicsCrm;kingswaysoft:url=https://test.crm3.dynamics.com;", connectionProps);

ResultSet resultSet = connection.getMetaData().getTables(null, null, null, null);
LOGGER.info(resultSet.toString());
TABLE_CAT,TABLE_SCHEM,TABLE_NAME,TABLE_TYPE,REMARKS
null,null,aaduser,Table,
null,null,account,Table,
null,null,accountleads,Table,
null,null,aciviewmapper,Table,
......

The getTables method returns the following metadata columns:

Column Name Data Type Description
TABLE_CAT String The catalog that contains the table, usually null for Dynamics.
TABLE_SCHEM String The schema of the table, also typically null for Dynamics.
TABLE_NAME String The name of the table name.
TABLE_TYPE String The type of the table (e.g., TABLE or VIEW).
REMARKS String An optional description of the table.

Columns

Use the getColumns method of the DatabaseMetaData interface to retrieve detailed information about the columns in the database. To narrow your search to a specific table, specify the table name as a parameter.

Class.forName("com.kingswaysoft.jdbc.Drivers");

Properties connectionProps = new Properties();
connectionProps.put("user", "username");
connectionProps.put("password", "password");

Connection connection = DriverManager.getConnection("jdbc:kingswaysoft:url=https://test.crm3.dynamics.com;", connectionProps);

ResultSet resultSet = connection.getMetaData().getColumns(null, null, "Contact", null);
LOGGER.info(resultSet.toString());
TABLE_CAT,TABLE_SCHEM,TABLE_NAME,COLUMN_NAME,DATA_TYPE,TYPE_NAME,COLUMN_SIZE,BUFFER_LENGTH,DECIMAL_DIGITS,NUM_PREC_RADIX,NULLABLE,COLUMN_DEF,SQL_DATA_TYPE,SQL_DATETIME_SUB,CHAR_OCTET_LENGTH,ORDINAL_POSITION,IS_NULLABLE,IS_AUTOINCREMENT,IS_GENERATEDCOLUMN,CRM_TYPE
null,null,account,accountcategorycode,4,java.lang.Integer,null,null,null,null,null,null,null,4,null,null,2,null,null,null,PicklistType
null,null,account,accountcategorycodename,12,java.lang.String,null,null,null,null,null,null,null,12,null,null,147,null,null,null,VirtualType
null,null,account,accountclassificationcode,4,java.lang.Integer,null,null,null,null,null,null,null,4,null,null,11,null,null,null,PicklistType
null,null,account,accountclassificationcodename,12,java.lang.String,null,null,null,null,null,null,null,12,null,null,140,null,null,null,VirtualType
null,null,account,accountid,12,java.lang.String,null,null,null,null,null,null,null,12,null,null,1,null,null,null,UniqueidentifierType
null,null,account,accountnumber,12,java.lang.String,20,null,null,null,null,null,null,12,null,null,23,null,null,null,StringType

The getColumns method returns the following columns:

Column Name Data Type Description
TABLE_CAT String The database name.
TABLE_SCHEM String The table schema.
TABLE_NAME String The table name.
COLUMN_NAME String The column name.
DATA_TYPE Integer The data type represented by a constant value from java.sql.Types.
TYPE_NAME String The data type name used by the driver.
COLUMN_SIZE Integer The length in characters of the column or the numeric precision.
BUFFER_LENGTH Integer The buffer length.
DECIMAL_DIGITS Integer The column scale or number of digits to the right of the decimal point.
NUM_PREC_RADIX Integer The radix, or base.
NULLABLE Integer Whether the column can contain null as defined by the following JDBC DatabaseMetaData constants: columnNoNulls (0) or columnNullable (1).
COLUMN_DEF String The default value for the column.
SQL_DATA_TYPE Integer Reserved by the specification.
SQL_DATETIME_SUB Integer Reserved by the specification.
CHAR_OCTET_LENGTH Integer The maximum length of binary and character-based columns.
ORDINAL_POSITION Integer The position of the column in the table, starting at 1.
IS_NULLABLE String Whether a null value is allowed: YES or NO.
IS_AUTOINCREMENT String Whether the column value is assigned by Dynamics in fixed increments.
IS_GENERATEDCOLUMN String Whether the column is generated: YES or NO.
DTS_TYPE String Dynamics DTS attribute type.

Primary Keys

The getPrimaryKeys method in the DatabaseMetaData interface is used to retrieve metadata about primary keys for a given table in Dynamics.

Class.forName("com.kingswaysoft.jdbc.Drivers");

Properties connectionProps = new Properties();
connectionProps.put("user", "username");
connectionProps.put("password", "password");

Connection connection = DriverManager.getConnection("jdbc:kingswaysoft:ServoceName=DynamicsCrm;url=https://test.crm3.dynamics.com;", connectionProps);

ResultSet resultSet = connection.getMetaData().getPrimaryKeys(null, null, "Contact");
LOGGER.info(resultSet.toString());
TABLE_NAME,PRIMARY_COLUMN_NAME
contact,contactid

The getPrimaryKeys method returns the following columns:

Column Name Data Type Description
TABLE_NAME String The name of the table that contains the primary key.
PRIMARY_COLUMN_NAME String The name of the column that serves as the primary key for the table.

Connection Settings

Connection Setting Data Type Default Value Description
AuthorizationServerUrl String "https://login.microsoftonline.com/" The AuthorizationServerUrl verifies identities, grants access based on permissions, issues secure tokens, and ensures compliance with security standards.
AzureTenant String "" The Azure Tenant ID used to access Dynamics.
CacheExpirationTime Integer 30 Defines the expiration time for cache. A value of 0 disables caching.
CertificatePassword String "" The password used to access the key store file.
ClientAppId String "" The ID (in GUID format) of the Azure Active Directory application you have created for application authentication.
ClientSecret String "" The client secret you have selected or created in Microsoft Azure Active Directory.
ConnectionTimeout Integer 30 ConnectionTimeout is the maximum amount of time the program will wait to set up a connection to the Dynamics API.
Domain String "" The domain used for Active Directory login authentication.
IgnoreCertificateErrors Boolean false Specifies whether to verify the certificate when connecting to Dynamics. If no certificate verification is required, you can set this value to 'true'. Note: This property only applies to RESTful calls.
IgnoreError Boolean false Determines if the program continues executing SQL statements after encountering an error.
LogFileSize String "10485760" A string specifying the maximum size in bytes for a log file.
LogLevel String "INFO" The logging level for the JDBC driver.
LogPath String "./jdbcLogs" The directory where log files are stored.
MatchHandling String "writeOne" The strategy employed to address situations where multiple records meet the search criteria. Strategies are case-sensitive and include "writeAll" which will affect all matches, "writeOne" which will affect the first match, "ignoreAll" which will ignore all matches, and "raiseError" which will raise an error when multiple matches are found. By default, it is set to 'writeOne'.
OemKey String "" The OEM License key.
Password String "" The password used to authenticate the user.
PathToCertificate String "" The file path where the keystore file for connecting to the Dynamics.
ProxyPassword String "" The password to be used to authenticate to the proxy.
ProxyServer String "" The host of the proxy server.
ProxyServerPort Integer 0 The port of the proxy server.
ProxyUserName String "" The username to be used to authenticate to the proxy.
ReadBatchSize Integer 1000 ReadBatchSize is used to set how many records can be read from Dynamics in a single call.
RedirectUri String "" The redirect URI used to obtain the Dynamics authentication URL.
ResultPath String "" The path where the execution result files are saved.
RetryOnIntermittentErrors Boolean true The RetryOnIntermittentErrors parameter indicates whether to retry the connection when it might occasionally fail due to temporary issues.
SaveResult Boolean false The SaveResult parameter indicates whether to save the execution results to a file.
ServerUrl String "" The URL for connecting to Dynamics.
ServiceTimeout Integer 120 ServiceTimeout is the timeout to receive the full response from Dynamics API.
Ssl Boolean false SSL indicates whether the connection is SSL-enabled or supports SSL encryption.
TokenPassword String "" The password used to read the token file.
TokenPath String "" The tokenPath specifies the file path where the token for connecting to Dynamics is located.
TotalThreads Integer 0 The number of threads for executing operations in parallel. A value of 0 will disable multi threading.
UserName String "" The user account used to connect to the server.
WriteBatchSize Integer 200 WriteBatchSize is used to set how many records can be written to Dynamics in a single call.