c# - 在控制台应用程序中加载 cmd

标签 c# mysql .net command-line

我有一个控制台应用程序,它执行一些命令并输出一些日志。

我需要显示命令及其结果的输出,如下所示:

>Loading the database...
>mysql -uUser -pPassword myDbName < mydumpFile
ERROR 1045 (28000): Access denied for user 'User'@'localhost' (using password: Y
ES)
>End loading the databse...

我做了以下事情:

void ImportData()
{
    Program.Log("INFO", "Start importing data... <<<");

    Process myProcess = new Process();
    string mySqlArgs = string.Format(" -u{0} -p{1} {2} < \"{3}\"", 
                                      bddUser, bddPassword, databaseName, dumpPath);
    ProcessStartInfo myProcessStartInfo = 
                                      new ProcessStartInfo("mysql", mySqlArgs);
    myProcessStartInfo.UseShellExecute = false;
    myProcessStartInfo.RedirectStandardOutput = true;
    myProcess.StartInfo = myProcessStartInfo;
    myProcess.Start();

    StreamReader reader = myProcess.StandardOutput;
    string theOutput = reader.ReadToEnd();
    if (theOutput.Length > 0)
        Program.Log("SQL", theOutput);

    Program.Log("INFO", "END importing data >>>");
}

但是这段代码

1) 不显示命令本身(仅显示结果)
2) 请求的格式可能应该是错误的,因为结果就像 mysql 命令中的格式错误

更新:新代码好一点

Program.Log("INFO", "Start importing Materials... <<<".Fill(code));

Process cmd = new Process();

cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;

cmd.Start();            

/* execute "mysql -uUser -pPassword base < dump" */
string mySqlCommand = "mysql -u{0} -p{1} {2} < \"{3}\"";
cmd.StandardInput.WriteLine(mySqlCommand, bddUser, bddPassword, databaseName, dumpPath);
cmd.StandardInput.Flush();
cmd.StandardInput.Close();

StreamReader reader = cmd.StandardOutput;
string theOutput = reader.ReadToEnd();
if (theOutput.Length > 0)
    Program.Log("SQL", Environment.NewLine + theOutput);

Program.Log("INFO", "END importing Materials >>>".Fill(code));

,但无论如何,它显示了 cmd.exe 第一次执行(mysql 命令之前)的附加信息,以及 mysql 命令结果之后的命令行...

最佳答案

执行脚本

 mysql -vvv -uUser ...

此选项将在脚本执行期间显示查询。

至于你的另一个问题:为什么你要调用cmd.exe?只需直接从程序中调用 mysql.exe 并跳过 shell...

关于c# - 在控制台应用程序中加载 cmd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26158737/

相关文章:

c# - 如何使用 .NET 和 Dapper.NET 执行此 sql 语句?

c# - 不可打印字符的序列化

C# 刷新动态标签上的值

mysql - 检查 MySQL 中日期范围的重叠

.net - Azure容器应用CORS问题

c# - 在上传 HTML5 vid 服务器端实现转换

php - 如何将当前日期插入数据库然后检索它?

php - 提取数据库信息并显示为 html 问题?

c# - 参数集合中已存在名为 'p__linq__0' 的参数。参数名称在参数集合中必须是唯一的

c# - 如何将 bool 值转换为本地化字符串