gpt4 book ai didi

c# - 如何通过 StreamReader -> StandardInput 使用 mysql.exe 导入大型 SQL 文件

转载 作者:可可西里 更新时间:2023-11-01 06:55:50 28 4
gpt4 key购买 nike

我有 .sql 文件 (550 MB),我想将它导入到正在运行的 mysql 服务器。我知道 mysql.exe 的路径。

我的想法是模仿命令行导入mysql -u user -ppass db_name < file.sql .这从命令行运行良好(我设置了高 max_allowed_pa​​cket)。根据 Stackoverflow 上的另一个线程,我发现这个工作正常:

Process process = new Process();
process.StartInfo.FileName = mysqlexepath;
process.StartInfo.Arguments = "-v -u user -ppassworddbname";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;

try
{
process.Start();
StreamWriter input = process.StandardInput;
using (StreamReader sr = new StreamReader(sqlfilepath))
{
while ((line = sr.ReadLine()) != null)
{
if (process.HasExited == true)
throw new Exception("DB went away.");

input.WriteLine(line);
input.Flush();
}
}
process.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

我可以看到如何在数据库中创建表。但我的问题是大约一半的过程退出。我在谷歌上搜索了一些超时设置,但找不到任何东西。

我也试过先读取文件:

var file = FileInfo(sqlfilepath);
StreamReader reader = file.OpenText();
string fileContents = reader.ReadToEnd();
StreamWriter input = process.StandardInput;
input.AutoFlush = true;
input.Write(fileContents);
input.Close();

但是我遇到了 OutOfMemory 异常。所以正确的方法不是通过字符串引导。

如果您能提供有关如何找出问题所在的任何建议,我将不胜感激。我什至不知道它的进程超时或 mysql 超时,或者问题是否出在 StreamReader 中。

最佳答案

我知道这不是您问题的直接答案,老实说,我不确定您的方法有什么问题。我可以通过分享我们如何使用 mysql.exe 运行非常大的 sql 脚本来提供帮助...

"C:\Program Files (x86)\MySQL\MySQL Server 5.0\bin\mysql.exe"-C -B --password=[密码] -P 3306 --user=[用户名] - -host=localhost --database=[数据库] -e "\.C:\Backups\Mybackup.sql"

这些参数大部分都是显而易见的,连接信息等。

不明显的是神奇的部分 -e "\. [filename]" -e 参数指定 mysql 应该运行以下命令并退出。前缀 "\. " 表示应使用输入文件,后跟该文件名。

我们使用它来毫无问题地恢复数 GB 的数据库。所以这里是使用 mssql 的完整“运行脚本”...

public static int RunMySql(string server, int port, string user, string password, string database, string filename)
{
var process = Process.Start(
new ProcessStartInfo
{
FileName = @"C:\Program Files (x86)\MySQL\MySQL Server 5.0\bin\mysql.exe",
Arguments =
String.Format(
"-C -B --host={0} -P {1} --user={2} --password={3} --database={4} -e \"\\. {5}\"",
server, port, user, password, database, filename),
ErrorDialog = false,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
WorkingDirectory = Environment.CurrentDirectory,
}
);

process.OutputDataReceived += (o, e) => Console.Out.WriteLine(e.Data);
process.ErrorDataReceived += (o, e) => Console.Error.WriteLine(e.Data);
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
process.StandardInput.Close();
process.WaitForExit();

return process.ExitCode;
}

关于c# - 如何通过 StreamReader -> StandardInput 使用 mysql.exe 导入大型 SQL 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13648523/

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