简体   繁体   English

在 C# 中使用 PowerShell 执行 MySql 查询

[英]Execute MySql Query using PowerShell in C#

I'm new to PowerShell.我是 PowerShell 的新手。 Is there a way in C# to call mysql.exe and execute a query using Powershell.在 C# 中有没有办法调用 mysql.exe 并使用 Powershell 执行查询。 I want to execute the query and covert the result into a csv file.我想执行查询并将结果转换为 csv 文件。

.\mysql.exe -C -B --host=amazonaws -P 3306 --user=user --password=pass --database=MyDB --execute="SELECT * FROM MyTable LIMIT 5" | Out-File "C:\output.sql" 

using (PowerShell PowerShellInstance = PowerShell.Create())
{        
  ????
  PowerShellInstance.Invoke();
}

Thanks谢谢

Of course connecting to MySQL database using C# it's easier but they want it to have a powershell script当然,使用 C# 连接到 MySQL 数据库更容易,但他们希望它有一个 powershell 脚本

 private static void GenerateNewInputFile(
        string server, 
        string user, 
        string password, 
        int port, 
        string database,
        string query,
        string mysqlLocation,
        string outputFilePath)
    {
        using (var powershell = PowerShell.Create())
        {
            var sb = new StringBuilder();
            sb.Append($"$server = \"{server}\"\n");
            sb.Append($"$user = \"{user}\"\n");
            sb.Append($"$password = \"{password}\"\n");
            sb.Append($"$port = {port}\n");
            sb.Append($"$db = \"{database}\"\n");
            sb.Append($"$query = \"{query}\"\n");
            sb.Append($"$mysql = \"{mysqlLocation}\"\n");
            sb.Append("$params = \"-C\",\"-B\",\"-h$server\",\"-P$port\",\"-u$user\",\"-p$password\",$db,\"-e$query\"\n");
            sb.Append($"&  $mysql @params | Out-File \"{outputFilePath}\"\n");

            powershell.AddScript(sb.ToString());

            powershell.Invoke();
        }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM