0

I am querying the version of sql server using sqlcmd (from my app) and would like to display the info, say, on a rich text box, how do i go about it, here's the code:

        Process proc = new Process();
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.RedirectStandardOutput = true;
        proc.StartInfo.FileName = "sqlcmd";
        proc.StartInfo.Arguments = @"-U sa -P somepassword -q 'SELECT @@VERSION' -S (localhost)\InstanceName";
        proc.Start();    


        StringBuilder q = new StringBuilder();
        while (!proc.HasExited)
        {
            q.Append(proc.StandardOutput.ReadToEnd());

        }
        string r = q.ToString();
        rtbCheckVersion.Text = r;
        proc.WaitForExit();
coder16
  • 21
  • 5
  • 1
    why are you executing the shutdown.exe program for that?? – Davide Piras May 07 '12 at 10:28
  • oops..just corrected the mistake – coder16 May 07 '12 at 10:29
  • 1
    possible duplicate of [How to redirect process output to System.String](http://stackoverflow.com/questions/3829749/how-to-redirect-process-output-to-system-string). Actually this question (in various variations, has been asked a couple of times. Hint: with your `while (!proc.HasExited)` you are over-complicating things. – Christian.K May 07 '12 at 10:31
  • 2
    Why you are using sqlcmd, why not simply connect to DB and execute 'SELECT @@VERSION' ? – Antonio Bakula May 07 '12 at 10:31
  • Hi Christian, you're actually right, it is sort of a duplicate. But how come am i not getting any output? – coder16 May 07 '12 at 10:32
  • @Antonio, connecting to DB is too much work for such a simple query... – coder16 May 07 '12 at 10:33
  • 1
    @coder16 Connecting to DB and performing the query yourself is actually much less CPU overhead than starting `sqlcmd`. I would say **"Redirecting process output is too much work for such a simple query"**. – Anders Marzi Tornblad May 07 '12 at 10:38

2 Answers2

2

since you have to execute a sql script, you could use SqlConnection and SqlCommand to get the output instead of starting a separated process.

check this answer and other answers in this question for some examples: https://stackoverflow.com/a/949933/559144

Community
  • 1
  • 1
Davide Piras
  • 43,984
  • 10
  • 98
  • 147
0

I see you don't want to use SqlConnection and SqlCommand...
I'm not sure, but it could be that your process exits before you get output.
Try this:

proc.Start();    
string s = proc.StandardOutput.ReadToEnd();
Marco
  • 56,740
  • 14
  • 129
  • 152
  • 2
    @coder16, you may also want to enable and read from `StandardError` in case "something" did not run as expected. – Tung May 07 '12 at 10:45
  • @Marco, got it: "Sqlcmd: '@@VERSION'': Unexpected argument. Enter '-?' for help.\r\n" looks like my arguments are incorrect... – coder16 May 07 '12 at 10:59