2

我不同意这个问题得到了有效的回答:decode mysqlbinlog in C#

我有,我认为是同样的问题:我想从 ac# 应用程序中读取 MySql 二进制日志,但不知道文件的格式。如何正确解析这些文件的数据?

4

1 回答 1

2

首先,我学到了什么:

  1. MySql 的大部分源代码文件与程序集一起安装,通常位于 [basedir]\include。例如,典型安装会将文件放在 Program Files\MySql\MySql 5.6\include 中。

  2. mysqlbin.cc 不在该文件夹中。但是,我可以通过快速的 Google 搜索轻松获得该文件。该文件可以在这里找到:https ://code.google.com/p/mg-common-utils/source/browse/trunk/myreplicator/src/mysqlbinlog.cc?r=4 。它有据可查,易于阅读。

二、我的解决方案:

正如akuzminsky 指出的,MySql 的binlog 的格式可能会发生变化。但是,从 mysqlbinlog.exe 实用程序返回的格式是一致的。此应用程序通常包含在 MySql 安装中,应位于 [basedir]\bin 中。我现在从 ac# Console Application 中运行此应用程序并解析结果。我使用以下步骤来完成此操作:

  1. 从选项文件中在 MySql 服务器上启用 binlogging。在 MySql Workbench 中,检查日志选项卡下的“log-bin”。或者,在设置文件中键入“log-bin=”(通常位于 [basedir] 中。可能称为“my.ini”或“my.cnf”或其他名称。通常,扩展名为 .cnf 或 .ini)。不需要文件名。如果没有指定,MySql 会自动为日志创建文件名。但是,请查看 MySql 文档以了解可能存在的问题。

  2. 在我的客户端应用程序中,我查询服务器以获取每个二进制日志的路径(可能有很多)。去做这个:

    query show global variables like 'datadir' //returns the data directory.
    query show binary logs //returns the filename of each binary log, along with its file size (helpful for reading).
    
    • 将这些一起解析得到每个二进制日志的路径。

  3. 由于 mysqlbinlog.exe 位于 [basedir]\bin 中,因此我查询服务器以获取基本目录的路径:

    query show global variables like 'basedir'
    

    然后,我用 '\bin\mysqlbinlog.exe' 解析结果

  4. 我使用 Process 类创建一个新进程,使用 mysqlbinlog.exe 执行每个二进制日志,并将每个文件结果读入一个字符串变量:

    private static string GetLogTexts(Liststring> logfilenames)
    {
        List<string> _logtexts = new List<string>();
        string _basedir = GetBaseDir();
        foreach(string logfilename in logfilenames)
        {
            Process proc = new Process();
            proc.StartInfo.FileName = _basedir + "\\bin\\mysqlbinlog";
            proc.StartInfo.Arguments = string.Format("\"{0}\"", logfile);
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardInput = proc.StartInfo.RedirectStandardOutput = true;
            proc.Start();
            _logtexts.Add(proc.StandardOutput.ReadToEnd());
        }
        return _logtexts;
    }
    private static string GetBaseDir()
    {
        string path = "";
        using (MySqlConnection conn = new MySqlConnection(RemoteServerConnectionString))
        {
            conn.Open();
            using (MySqlCommand cmd1 = new MySqlCommand("show global variables like 'basedir'", conn))
            {
                using (MySqlDataReader reader = cmd1.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        path = reader.GetString(1);
                    }
                }
            }
        }
        return path;
    }
    
  5. 最后,我使用自己的逻辑(特定于我要查找的内容)解析结果。结果非常容易阅读:mysqlbinlog 使用常规换行符,语句由分隔符终止,分隔符在语句之前定义(通常可以有多个分隔符)。

我希望这可以帮助别人!

于 2014-02-18T17:36:54.007 回答