Home > Net >  How to run sqlite3 inline command using c#?
How to run sqlite3 inline command using c#?

Time:10-09

When I run the below command in cmd prompt of windows:

sqlite3 -header -csv local-DataBase.sqlite "select * from customers;" > data.csv

It creates a file called "data.csv" with the result of "select * from customers;" in it with headers. I need to run the same command as above in c# so that it the console app creates a file for the result of the sql command.

Till now I have done this:

 string sqlLite3ExePath = "sqlite3";
 string sqLitePath2 = "-header -csv local-DataBase.sqlite \"select* from customers;\" > data.csv";

 using (Process pProcess = new Process())
                {
                    pProcess.StartInfo.FileName = sqlLite3ExePath;
                    pProcess.StartInfo.Arguments = sqLitePath2 ;
                    pProcess.StartInfo.UseShellExecute = false;
                    pProcess.StartInfo.RedirectStandardOutput = true;
                    pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                    pProcess.StartInfo.CreateNoWindow = false;
                    pProcess.EnableRaisingEvents = true;
                    pProcess.Exited  = PProcess_Exited;
                    pProcess.Start();
                    string output = pProcess.StandardOutput.ReadToEnd(); 
                    pProcess.WaitForExit();    
                    Debug.WriteLine(output);
                }
       

But this throws an error:

Error: near ">": syntax error

What am I doing wrong?

CodePudding user response:

As mentioned in the comments, there are two things going on when you run this command from the command prompt, you're running SQLite, but because of the redirect operator, you're also having the shell capture the output and create a file for you.

If you want to recreate this exact behavior, you need to run the shell and pass it this command:

    string sqlLite3ExePath = "cmd";
    string sqLitePath2 = "/c \"sqlite3 -header -csv local-DataBase.sqlite ^\"select* from customers;^\" > data.csv\"";

    using (var pProcess = new Process())
    {
        pProcess.StartInfo.FileName = sqlLite3ExePath;
        pProcess.StartInfo.Arguments = sqLitePath2;
        pProcess.StartInfo.UseShellExecute = false;
        pProcess.StartInfo.RedirectStandardOutput = true;
        pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
        pProcess.StartInfo.CreateNoWindow = false;
        pProcess.EnableRaisingEvents = true;
        pProcess.Exited  = PProcess_Exited;
        pProcess.Start();
        string output = pProcess.StandardOutput.ReadToEnd();
        pProcess.WaitForExit();
        Console.WriteLine(output);
    }
  • Related