gpt4 book ai didi

c# - 读取 MySql binlog

转载 作者:行者123 更新时间:2023-11-29 06:40:31 33 4
gpt4 key购买 nike

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

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

最佳答案

首先,我学到了什么:

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

  2. mysqlbin.cc 不在该文件夹中。但是,我可以通过快速谷歌搜索轻松获得该文件。该文件可在此处找到: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 中。我现在从 c# 控制台应用程序中运行此应用程序并解析结果。我使用以下步骤来完成此操作:

  1. 从选项文件中在 MySql 服务器上启用二进制日志。在 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 使用常规换行符,语句以定界符终止,该定界符定义在语句之前(通常,可以有多个定界符)。

我希望这对某人有帮助!

关于c# - 读取 MySql binlog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21838089/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com