Querying Data in an external Database using QuerySelect in the .NET API.

Less than one minute read time.

Querying Data in an external Database using QuerySelect in the .NET API.

In the COM API you can specify the target database you want to run a query against using CreateQueryObj.

For example

[code language="javascript"]
CRM.CreateQueryObj ("select * from contacts","panoplytech");
[/code]

This uses the Advanced Customization->Tables and Databases->Database connection.

But how can we do this in the .Net API? The QuerySelect object only has the single parameter.

Below is some example code that shows how the QuerySelect works

[code language="csharp"]
string strSQL = "select * from company where type = 'supplier'";
QuerySelect queryObj = new QuerySelect();
queryObj.SQLCommand = strSQL;
queryObj.ExecuteReader();
while (!queryObj.Eof())
{
AddContent(queryObj.FieldValue("comp_name"));
AddContent("
");
queryObj.Next();
}
[/code]

It is correct to observe that there is no 'database' parameter option as when the ASP page equivalent is used but you can pass a fully qualified SQL statement that is directed to another database e.g.

[code language="csharp"]
select * from panoplytech.dbo.contacts where type = 'supplier'
[/code]

So the same code that accesses an external database would be

[code language="csharp"]
string strSQL = "select * from panoplytech.dbo.contacts where type = 'supplier'";
QuerySelect queryObj = new QuerySelect();
queryObj.SQLCommand = strSQL;
queryObj.ExecuteReader();
while (!queryObj.Eof())
{
AddContent(queryObj.FieldValue("companyname"));
AddContent("
");
queryObj.Next();
}
[/code]