.NET 幫助

MySqlclient C#(開發人員如何使用)

發佈 2024年4月29日
分享:

數據報告和可視化是當今軟件環境中許多應用程式的重要組成部分,提供有關用戶行為、性能指標和業務關鍵績效指標(KPI)的洞察。 MySqlClient 是一個適用於 .NET 的 MySql 庫,它允許開發者輕鬆連接 MySql 資料庫,這些資料庫經常用於在線應用中存儲和管理數據。

相反, IronPDF 是一個受歡迎的 .NET 函式庫,用於創建和修改 PDF 文件。IronPDF 是一個有用的數據報告和文檔生成任務解決方案,因為它允許開發人員從其 .NET 應用程式內創建動態 PDF 報告、發票、報表等。

本文探討了集成 MySqlClientIronPDF 在 .NET 應用程式中啟用高效的數據報告。通過結合這些技術,開發人員可以簡化從 MySql 數據庫中查詢數據並生成視覺上吸引人的 PDF 報告的過程,使使用者能夠根據數據驅動的見解做出明智的決策。

如何使用 MySqlclient

  1. 在中創建一個新的C#項目 Visual Studio.

  2. 從NuGet安裝MySqlClient庫。

  3. 打開連接到MySql資料庫。

  4. 執行查詢並獲取結果。

  5. 處理數據並關閉對象。

MySqlClient 簡介

開發 .NET 應用程式需要使用 MySQLClient,特別是在處理 MySQL 資料庫時。它通過作為應用程式程式碼和 MySQL 資料庫伺服器之間的橋樑,促進各種資料庫活動的無縫執行。這包括執行 SQL 查詢、獲取資訊、編輯資料庫條目以及維護資料庫連線。MySQL Python 也可用,這使我們能夠在虛擬環境中安裝它們。

MySqlClient 的優勢

資料庫連接: 從 .NET 程式中,MySqlClient 提供類別和方法來連接到 MySql 資料庫伺服器。開發人員可以提供資料庫名稱、登錄名、密碼和伺服器地址等連接詳情來創建連接。

SQL 操作: 一旦建立了連接,開發人員可以使用 MySqlClient 對 MySql 資料庫執行 SQL 查詢。這涵蓋了使用 SELECT 查詢檢索數據以及使用 INSERT、UPDATE、DELETE 和其他數據操作查詢更改資料庫記錄。

防止 SQL 攻擊: MySqlClient 支持參數化查詢,使得 SQL 注入攻擊可以避免並且安全的參數傳遞到 SQL 查詢成為可能。由於參數化查詢將 SQL 功能與用戶輸入隔離開來,安全性得到了提高。

使用 C# 中的 MySQLClient,在安裝或依賴解析過程中可能會遇到例如「Failed building wheel for MySQLClient」的錯誤,這表明 MySQLClient 套件或其依賴項可能存在潛在問題。如果成功的話,該庫將被保存在程序文件位置。

開始使用MySqlclient

在 Visual Studio 中創建新專案

要打開 Visual Studio 應用程式,請選擇「檔案」選單。選擇「新專案」後,選擇「主控台應用程式」。

MySqlclient C# (開發者使用方式):圖 1 - Visual Studio 應用程式頁面:選擇「新專案」- 選擇「主控台應用程式」

選擇檔案位置後,在指定的文字欄位中輸入專案名稱。接下來,選擇所需的 .NET Framework 後,點擊建立按鈕,如下圖所示。

MySqlclient C#(開發人員如何使用):圖 2 - 接下來,通過指定所需的項目名稱和文件夾路徑位置來配置您的項目。選擇對應的 .NET Framework 並點擊“Create”按鈕。

Visual Studio 專案的組織方式將取決於所選應用程式。要向應用程式添加程式碼並構建它,只需打開 program.cs 文件。您有三個選項:線上應用程式、控制台或 Windows。

然後可以添加庫並測試程式碼。

在 C# 專案中安裝 MySqlClient

在 C# 專案中整合 MySqlClient 非常簡單,必須使用微軟的 .NET 套件管理工具 NuGet 來安裝 MySql.Data 套件。此套件提供了整合 MySqlClient 到您的應用程式中所需的工具和資源。

MySqlclient C#(開發人員的使用方式):圖 3 - 使用「管理解決方案的 NuGet 套件」來安裝 MySql.Data,首先在 NuGet 套件管理器的搜尋欄位中搜尋「MySql.Data」,然後選擇專案並點擊安裝按鈕。

在 .NET 應用程式中實作 MySqlClient

幾種類型的 .NET 應用程式,例如 Windows Forms (WinForms) 和 Windows 控制台相容,並與 MySqlClient 兼容。任何框架的基本理念,儘管在實現上有所不同,始終是相同的:使用您的應用程式來進行不同種類的資料庫操作。

使用 MySqlClient 操作的基本示例

在與 MySql 數據庫交互之前,先與 MySqlClient 建立連接。接下來,執行 SQL 查詢以從 MySql 檢索數據。執行 SQL 查詢的一個工具是 MySqlCommand。

using MySql.Data.MySqlClient;
using System.Text;
class Program
{
    static void Main(string [] args)
    {
        try
        {
            // my sql client connection string
            string connString = "server=myServerAddress;user=myUsername;Password=myPassword;Database=myDatabase";
            // Create connection object
            MySqlConnection conn = new MySqlConnection(connString);
            // Open the connection
            conn.Open();
            // SQL query
            string sql = "SELECT * FROM myTable";
            // Create MySqlCommand
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            // Execute the command and retrieve data
            MySqlDataReader reader = cmd.ExecuteReader();
            // Loop through the retrieved data
            while (await reader.ReadAsync())
            {
                // Retrieve data from the data reader
                string name = reader ["Name"].ToString();
                int age = Convert.ToInt32(reader ["Age"]);
                Console.WriteLine($"Name: {name}, Age: {age}");
            }
            // Close the connection when done
            conn.Close();
            // exit status
        }
        catch(Exception ex)
        {
            // mysqlclient failed message here
            Console.WriteLine(ex.ToString());
    // console the error message
        }
// exit code
    }
}
using MySql.Data.MySqlClient;
using System.Text;
class Program
{
    static void Main(string [] args)
    {
        try
        {
            // my sql client connection string
            string connString = "server=myServerAddress;user=myUsername;Password=myPassword;Database=myDatabase";
            // Create connection object
            MySqlConnection conn = new MySqlConnection(connString);
            // Open the connection
            conn.Open();
            // SQL query
            string sql = "SELECT * FROM myTable";
            // Create MySqlCommand
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            // Execute the command and retrieve data
            MySqlDataReader reader = cmd.ExecuteReader();
            // Loop through the retrieved data
            while (await reader.ReadAsync())
            {
                // Retrieve data from the data reader
                string name = reader ["Name"].ToString();
                int age = Convert.ToInt32(reader ["Age"]);
                Console.WriteLine($"Name: {name}, Age: {age}");
            }
            // Close the connection when done
            conn.Close();
            // exit status
        }
        catch(Exception ex)
        {
            // mysqlclient failed message here
            Console.WriteLine(ex.ToString());
    // console the error message
        }
// exit code
    }
}
Imports MySql.Data.MySqlClient
Imports System.Text
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Try
			' my sql client connection string
			Dim connString As String = "server=myServerAddress;user=myUsername;Password=myPassword;Database=myDatabase"
			' Create connection object
			Dim conn As New MySqlConnection(connString)
			' Open the connection
			conn.Open()
			' SQL query
			Dim sql As String = "SELECT * FROM myTable"
			' Create MySqlCommand
			Dim cmd As New MySqlCommand(sql, conn)
			' Execute the command and retrieve data
			Dim reader As MySqlDataReader = cmd.ExecuteReader()
			' Loop through the retrieved data
			Do While Await reader.ReadAsync()
				' Retrieve data from the data reader
				Dim name As String = reader ("Name").ToString()
				Dim age As Integer = Convert.ToInt32(reader ("Age"))
				Console.WriteLine($"Name: {name}, Age: {age}")
			Loop
			' Close the connection when done
			conn.Close()
			' exit status
		Catch ex As Exception
			' mysqlclient failed message here
			Console.WriteLine(ex.ToString())
	' console the error message
		End Try
' exit code
	End Sub
End Class
VB   C#

上述程式碼片段使用 MySqlClient 從 MySql 資料庫中獲取數據並顯示在控制台上。查詢結果顯示在下圖中。

MySqlclient C#(開發人員如何使用): 圖 4 - 控制台輸出顯示使用MySqlClient包從MySql資料庫中讀取的姓名和年齡在 .NET 項目中

MySqlClient 操作與 MySql

使用 MySql 的參數化查詢

參數化查詢通過允許數據庫服務器緩存查詢計劃來提高查詢性能並減少 SQL 注入攻擊的風險。MySqlClient 提供部分查詢支持。此外,參數化查詢使得以安全且有效的方式處理動態 SQL 查詢變得更加容易。

使用 PostgreSQL 進行批量操作

MySqlClient 支援批量插入、更新和刪除操作,這在處理大型數據集時可以顯著提高速度。當多行可在單個數據庫事務中處理時,批量操作減少了與數據庫伺服器進行單獨數據傳輸的開銷。

處理事務

如果您的操作需要將多個 SQL 語句作為一個協調單位來執行,您可以利用事務來實現。

與 MySql 資料庫的連接

只需幾行代碼,MySqlClient 就能幫助您連接到 MySql 資料庫伺服器。

MySqlConnection conn = new MySqlConnection(connString);
MySqlConnection conn = new MySqlConnection(connString);
Dim conn As New MySqlConnection(connString)
VB   C#

上述代碼幫助我們連接到 MySql 伺服器。

將 MySqlClient 與 IronPDF 整合

使用 MySqlClient 和 IronPDF 一起

結合 IronPDFMySqlClient 在 C# 專案中開啟了令人興奮的新可能性。IronPDF 是將此內容轉換為 PDF 的一個極佳工具,即使 MySqlClient 是一個出色的工具來與 MySql 互動。由於這種連接性,程式設計師可以創建能夠與資料庫互動並從這些內容創建 PDF 的應用程式。

使用 IronPDF 獲取 MySql 數據

您可以使用 MySqlClient 創建 Windows 控制台應用程序,允許用戶在您的應用程序中與數據庫交互。首先,為您的應用程序提供數據庫訪問權限。此控件應適合控制台,並留有足夠的空間進行數據庫交互。還需添加批量操作和數據類型映射。

安裝 IronPDF

  • 啟動 Visual Studio 專案。
  • 選擇「工具」>「NuGet 套件管理器」>「套件管理器主控台」。

    • 在套件管理器主控台中輸入以下命令並按下 Enter 鍵:
Install-Package IronPdf
  • 或者您可以使用 NuGet 套件管理器來安裝 IronPDF。

    • 在搜尋結果中瀏覽 IronPDF 套件,選擇它,然後點擊「安裝」按鈕。Visual Studio 將自動處理下載和安裝。

MySqlclient C#(開發人員如何使用):圖 5 - 安裝 IronPDF,使用 NuGet 套件管理器中的「為解決方案管理 NuGet 套件」,在搜索欄中搜索 IronPdf,然後選擇項目並點擊安裝按鈕。

  • 透過 NuGet,IronPDF 套件及任何專案所需的依賴項目將會被下載並安裝。
  • 安裝完成後,可以在您的專案中使用 IronPDF。

透過 NuGet 網站安裝

訪問 NuGet 網站上的 IronPDF 頁面 https://www.nuget.org/packages/IronPdf,了解更多有關 IronPDF 的功能、相容性和其他下載選項。

利用 DLL 安裝

或者,您可以通過使用 IronPDF 的 DLL 檔案直接將其整合到您的專案中。要下載包含 DLL 的 ZIP 檔案,請點擊此 連結一旦解壓縮後,將DLL包含在您的專案中。

實現邏輯

  • 建立連接: 首先使用 MySqlClient 建立與 MySQL 資料庫的連接。初始化一個 MySqlConnection 物件,並提供必要的連接字串,其中包含伺服器地址、資料庫名稱、用戶名和密碼等詳細資訊。
  • 執行查詢: 可以使用 MySQLClient 在 MySQL 資料庫上運行 SQL 查詢。MySqlCommand 支援準備和執行 SQL 語句。要運行 SELECT 查詢並獲取資料,請使用 MySqlCommand 或 ExecuteReader(). 使用 ExecuteNonQuery() 執行 INSERT、UPDATE、DELETE 等非查詢語句。
  • 檢索資料: 一旦使用 MySqlClient 從 MySql 檢索到資料後,您可以利用 IronPDF 動態生成 PDF 報告。IronPDF 提供了創建 PDF 文件、添加文本、圖像和表格等內容,並將輸出 PDF 文件保存到磁碟或記憶體流中的功能。
  • 生成報告: 自定義由 IronPDF 生成的 PDF 報告程式文件的外觀和佈局,以滿足您的文件或應用程式的具體要求。您可以使用 CSS 樣式、HTML 模板和 IronPDF 的 API 添加頁眉、頁腳、頁碼和其他元素到您的 PDF 文件中。
static void Main(string [] args)
    {
        StringBuilder sb = new StringBuilder();
        var Renderer = new ChromePdfRenderer(); // Instantiates Chrome Renderer
        sb.Append("<h1>Dynamic PDF Generated from MySqlClient Data</h1>");
    //sqlclient connection and command code here
        while (await reader.ReadAsync())
        {
            // Retrieve data from the data reader
            string name = reader ["Name"].ToString();
            int age = Convert.ToInt32(reader ["Age"]);
            // Add data to the PDF
            sb.Append($"<p>Name: {name}, Age: {age}</p>");
        }
        var pdf = Renderer.RenderHtmlAsPdf(sb.ToString());
        // Save the PDF document
        pdf.SaveAs("output.pdf");
        // Close the connection when done
        conn.Close();
    }
static void Main(string [] args)
    {
        StringBuilder sb = new StringBuilder();
        var Renderer = new ChromePdfRenderer(); // Instantiates Chrome Renderer
        sb.Append("<h1>Dynamic PDF Generated from MySqlClient Data</h1>");
    //sqlclient connection and command code here
        while (await reader.ReadAsync())
        {
            // Retrieve data from the data reader
            string name = reader ["Name"].ToString();
            int age = Convert.ToInt32(reader ["Age"]);
            // Add data to the PDF
            sb.Append($"<p>Name: {name}, Age: {age}</p>");
        }
        var pdf = Renderer.RenderHtmlAsPdf(sb.ToString());
        // Save the PDF document
        pdf.SaveAs("output.pdf");
        // Close the connection when done
        conn.Close();
    }
Shared Sub Main(ByVal args() As String)
		Dim sb As New StringBuilder()
		Dim Renderer = New ChromePdfRenderer() ' Instantiates Chrome Renderer
		sb.Append("<h1>Dynamic PDF Generated from MySqlClient Data</h1>")
	'sqlclient connection and command code here
		Do While Await reader.ReadAsync()
			' Retrieve data from the data reader
			Dim name As String = reader ("Name").ToString()
			Dim age As Integer = Convert.ToInt32(reader ("Age"))
			' Add data to the PDF
			sb.Append($"<p>Name: {name}, Age: {age}</p>")
		Loop
		Dim pdf = Renderer.RenderHtmlAsPdf(sb.ToString())
		' Save the PDF document
		pdf.SaveAs("output.pdf")
		' Close the connection when done
		conn.Close()
End Sub
VB   C#

以下是由上述程式碼生成的報告。

MySqlclient C#(開發人員如何運作):圖 6 - 使用 MySqlClient 和 IronPDF 從 MySql 資料庫數據生成的輸出 PDF。

要了解更多關於 IronPDF 代碼,請參考 這裡.

結論

IronPDF與...的連接 MySqlClient 在 .NET 應用程式中提供了一個強大的選項,用於有效的數據報告。通過使用 IronPDF 來創建美觀的 PDF 報告和 MySQLClient 從 MySql 資料庫中查詢數據,開發人員可以加速數據可視化和報告的過程,為用戶提供有洞察力的信息。

在 .NET 應用程式中訪問 MySql 資料庫數據時,MySqlClient 提供了一個強大的基礎,其廣泛的工具可以用於查詢、修改和管理數據。當與 IronPDF 生成的動態和可配置的 PDF 報告結合使用時,開發人員可以生成專業的報表,並且這些報表可以根據客戶和應用程式的需求進行定制。

749 美元的 Lite 套餐包括永久許可證、一年的軟體維護和圖書館升級。IronPDF 提供 免費授權 了解更多有關成本和授權的資訊。若要了解 Iron Software 提供的其他軟體產品,請點擊此處 頁面.

< 上一頁
C# 記錄與類別 (開發人員運作方式)
下一個 >
TCP .NET(如何為開發人員工作)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >