文件首頁
MySQL Connector/NET 開發人員指南
相關文件 下載本手冊
PDF (US Ltr) - 1.3Mb
PDF (A4) - 1.3Mb


5.12.2.1 檢視 MySQL 追蹤資訊

本節說明如何設定您的應用程式以檢視 MySQL 追蹤資訊。

您需要做的第一件事是為您的應用程式建立適當的 app.config 檔案。例如

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.diagnostics>
    <sources>
      <source name="mysql" switchName="SourceSwitch"
        switchType="System.Diagnostics.SourceSwitch" >
        <listeners>
          <add name="console" />
          <remove name ="Default" />
        </listeners>
      </source>
    </sources>
    <switches>
      <!-- You can set the level at which tracing is to occur -->
      <add name="SourceSwitch" value="Verbose" />
      <!-- You can turn tracing off -->
      <!--add name="SourceSwitch" value="Off" -->
    </switches>
    <sharedListeners>
      <add name="console"
        type="System.Diagnostics.ConsoleTraceListener"
        initializeData="false"/>
    </sharedListeners>
  </system.diagnostics>
</configuration>

此組態可確保建立適當的追蹤來源以及切換。在本例中,切換層級設定為 Verbose 以顯示最大量的資訊。

接下來,在您的 C# 應用程式中,將 logging=true 加入連接字串。例如

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using MySql.Data;
using MySql.Data.MySqlClient;
using MySql.Web;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            string connStr = "server=localhost;user=root;database=world;port=3306;password=******;logging=true";
            MySqlConnection conn = new MySqlConnection(connStr);
            try
            {
                Console.WriteLine("Connecting to MySQL...");
                conn.Open();

                string sql = "SELECT Name, HeadOfState FROM Country WHERE Continent='Oceania'";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                MySqlDataReader rdr = cmd.ExecuteReader();

                while (rdr.Read())
                {
                    Console.WriteLine(rdr[0] + " -- " + rdr[1]);
                }

                rdr.Close();

                conn.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.WriteLine("Done.");
        }
    }
}

這個簡單的應用程式接著會產生下列輸出

Connecting to MySQL...
mysql Information: 1 : 1: Connection Opened: connection string = 'server=localhost;User Id=root;database=world;port=3306
;password=******;logging=True'
mysql Information: 3 : 1: Query Opened: SHOW VARIABLES
mysql Information: 4 : 1: Resultset Opened: field(s) = 2, affected rows = -1, inserted id = -1
mysql Information: 5 : 1: Resultset Closed. Total rows=272, skipped rows=0, size (bytes)=7058
mysql Information: 6 : 1: Query Closed
mysql Information: 3 : 1: Query Opened: SHOW COLLATION
mysql Information: 4 : 1: Resultset Opened: field(s) = 6, affected rows = -1, inserted id = -1
mysql Information: 5 : 1: Resultset Closed. Total rows=127, skipped rows=0, size (bytes)=4102
mysql Information: 6 : 1: Query Closed
mysql Information: 3 : 1: Query Opened: SET character_set_results=NULL
mysql Information: 4 : 1: Resultset Opened: field(s) = 0, affected rows = 0, inserted id = 0
mysql Information: 5 : 1: Resultset Closed. Total rows=0, skipped rows=0, size (bytes)=0
mysql Information: 6 : 1: Query Closed
mysql Information: 10 : 1: Set Database: world
mysql Information: 3 : 1: Query Opened: SELECT Name, HeadOfState FROM Country WHERE Continent='Oceania'
mysql Information: 4 : 1: Resultset Opened: field(s) = 2, affected rows = -1, inserted id = -1
American Samoa -- George W. Bush
Australia -- Elisabeth II
...
Wallis and Futuna -- Jacques Chirac
Vanuatu -- John Bani
United States Minor Outlying Islands -- George W. Bush
mysql Information: 5 : 1: Resultset Closed. Total rows=28, skipped rows=0, size (bytes)=788
mysql Information: 6 : 1: Query Closed
Done.
mysql Information: 2 : 1: Connection Closed

追蹤訊息中顯示的第一個數字對應至 MySQL 事件類型。追蹤訊息中顯示的第二個數字是連線計數。下表描述每個 MySQL 事件類型。

事件類型 描述
1 ConnectionOpened:連接字串
2 ConnectionClosed
3 QueryOpened:mysql 伺服器執行緒 ID、查詢文字
4 ResultOpened:欄位計數、受影響的資料列 (-1 如果是選取)、插入的 ID (-1 如果是選取)
5 ResultClosed:讀取的資料列總數、略過的資料列、結果集中位元組的大小
6 QueryClosed
7 StatementPrepared:準備好的 SQL、語句 ID
8 StatementExecuted:語句 ID、mysql 伺服器執行緒 ID
9 StatementClosed:語句 ID
10 NonQuery:[不同]
11 UsageAdvisorWarning:使用建議器旗標。NoIndex = 1、BadIndex = 2、SkippedRows = 3、SkippedColumns = 4、FieldConversion = 5。
12 Warning:層級、代碼、訊息
13 Error:錯誤編號、錯誤訊息

雖然此範例使用 ConsoleTraceListener,但可以使用任何其他標準接聽程式。另一種可能性是建立自訂接聽程式,該接聽程式使用 TraceEvent 方法傳遞的資訊。例如,可以建立自訂追蹤接聽程式來執行 MySQL 事件訊息的主動監控,而不只是將這些訊息寫入輸出裝置。

也可以在執行階段將接聽程式新增至 MySQL 追蹤來源。這可以使用下列程式碼完成

MySqlTrace.Listeners.Add(new ConsoleTraceListener());

Connector/NET 提供在執行階段開啟和關閉追蹤的功能。這可以使用呼叫 MySqlTrace.EnableQueryAnalyzer(string host, int postInterval)MySqlTrace.DisableQueryAnalyzer() 來實現。參數 host 是要監控的 MySQL Enterprise Monitor 伺服器的 URL。參數 postInterval 是將資料張貼到 MySQL Enterprise Monitor 的頻率,以秒為單位。