在 Crystal Reports 中创建报表时,有两个选项可用于在设计报表时访问 MySQL 数据。
第一个选项是在设计报表时使用连接器/ODBC 作为 ADO 数据源。您将能够浏览您的数据库并使用拖放来选择表格和字段来构建您的报告。这种方法的缺点是必须在您的应用程序中执行额外的工作才能生成与报告预期的数据集相匹配的数据集。
第二种选择是在 VB.NET 中创建数据集并将其保存为 XML。然后可以使用此 XML 文件来设计报告。这在您的应用程序中显示报告时效果很好,但在设计时不太通用,因为您必须在创建数据集时选择所有相关列。如果您忘记了某个列,则必须先重新创建数据集,然后才能将该列添加到报告中。
以下代码可用于从查询创建数据集并将其写入磁盘:
C# 代码示例
DataSet myData = new DataSet();
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataAdapter myAdapter;
conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();
myAdapter = new MySql.Data.MySqlClient.MySqlDataAdapter();
conn.ConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=12345;database=test";
try
{
cmd.CommandText = "SELECT city.name AS cityName, city.population AS CityPopulation, " +
"country.name, country.population, country.continent " +
"FROM country, city ORDER BY country.continent, country.name";
cmd.Connection = conn;
myAdapter.SelectCommand = cmd;
myAdapter.Fill(myData);
myData.WriteXml(@"C:\dataset.xml", XmlWriteMode.WriteSchema);
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message, "Report could not be created",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Visual Basic 代码示例
Dim myData As New DataSet
Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
conn.ConnectionString = "server=127.0.0.1;" _
& "uid=root;" _
& "pwd=12345;" _
& "database=world"
Try
conn.Open()
cmd.CommandText = "SELECT city.name AS cityName, city.population AS CityPopulation, " _
& "country.name, country.population, country.continent " _
& "FROM country, city ORDER BY country.continent, country.name"
cmd.Connection = conn
myAdapter.SelectCommand = cmd
myAdapter.Fill(myData)
myData.WriteXml("C:\dataset.xml", XmlWriteMode.WriteSchema)
Catch ex As Exception
MessageBox.Show(ex.Message, "Report could not be created", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
生成的 XML 文件可在设计报表时用作 ADO.NET XML 数据源。
如果您选择使用连接器/ODBC 设计您的报告,它可以从 dev.mysql.com下载。