如何在运行时更改Crystal Report的ODBC数据库连接?

Rya*_*lor 10 postgresql odbc database-connection crystal-reports

我有一份使用Crystal Reports 2008的报告,我需要部署一个生产系统,这意味着我需要能够在运行时更改数据库连接.数据库是PostgreSQL 8.3.0,我用来创建初始报告的连接是ODBC连接.

我找到了各种方法来更改数据库连接,包括以下内容:

reportDoc.Load(report);
reportDoc.DataSourceConnections[0].SetConnection("server", "database", "user", "pwd");
reportDoc.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, path);
Run Code Online (Sandbox Code Playgroud)

但是,这始终失败,并显示以下错误消息.

无法打开连接.

我已经通过pgAdmin III成功连接到数据库来验证连接参数,因此我知道连接参数是正确的.另外,如果我删除了SetConnection(...)行,那么代码如下所示:

reportDoc.Load(report);
reportDoc.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, path);
Run Code Online (Sandbox Code Playgroud)

然后使用报告中存储的连接参数运行报告.是否可能此方法不适用于ODBC连接?

如何在运行时更改Crystal Report的ODBC数据库连接?

Rya*_*lor 16

经过更多的研究,我发现有两个部分的答案.

第1部分

如果您使用数据所有者通过ODBC连接到PostgreSQL(Crystal Reports可以在撰写本文时从PostgreSQL中提取数据的唯一方法),那么您可以使用以下代码:

reportDoc.Load(report);
reportDoc.DataSourceConnections[0].SetConnection("Driver={PostgreSQL ANSI};Server=myServer;Port=5432;", "myDatabase", "myUser", "myPassword");
reportDoc.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, path);
// Depending on your application you may have more than one data source connection that needs to be changed.
Run Code Online (Sandbox Code Playgroud)

此方法仅在您作为拥有您要报告的数据的用户进行连接时才有效,因为不需要提供模式名称.

第2部分

如果您通过ODBC与数据所有者以外的用户连接到PostgreSQL,则需要手动提供模式名称.这是通过以下代码完成的.

reportDoc.Load(report);

ConnectionInfo connInfo = new ConnectionInfo();
connInfo.ServerName = "Driver={PostgreSQL ANSI};Server=myServer;Port=5432;";
connInfo.DatabaseName = "myDatabase";
connInfo.UserID = "myUser";
connInfo.Password = "myPassword";

TableLogOnInfo tableLogOnInfo = new TableLogOnInfo();
tableLogOnInfo.ConnectionInfo = connInfo;

foreach (Table table in reportDoc.Database.Tables)
{
    table.ApplyLogOnInfo(tableLogOnInfo);
    table.LogOnInfo.ConnectionInfo.ServerName = connInfo.ServerName;
    table.LogOnInfo.ConnectionInfo.DatabaseName = connInfo.DatabaseName;
    table.LogOnInfo.ConnectionInfo.UserID = connInfo.UserID;
    table.LogOnInfo.ConnectionInfo.Password = connInfo.Password;

    // Apply the schema name to the table's location
    table.Location = "mySchema." + table.Location;
}

reportDoc.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, path);
Run Code Online (Sandbox Code Playgroud)

摘要

尝试从Crystal Reports连接到PostgreSQL数据库时,有两个关键信息.

  1. 必须在服务器名称属性中指定驱动程序,服务器和端口号.
  2. 如果以数据所有者以外的用户身份进行连接,则必须为要从中提取数据的每个表指定模式名称.

来源

有几个使用的来源没有在我的具体情况下有效的答案,但这使我朝着正确的方向前进.这些来源如下.