Question

I've been trying to use ShellExecute from within a Delphi app to open Mysql and run a script.

ShellExecute(Handle, 'open', PWideChar(InpCommandProgram.text),
    PWideChar(commandline), nil, SW_SHOWNORMAL);

InpCommandProgram.text = 'MYSQL'
commandline = '--user=root --password=password < C:/directory/filename.sql '

filename.sql has been stripped down to 'Create databasename'.

A command window opens briefly and scrolls some messages - too fast to read. If I open a command window and enter the same program and commandline it works. I can't see the error messages when it fails.

I'm running locally on a Windows 7 desktop. I tried directing output to a log file, but I don't even get the file in batch. I do get a log when it is successful interactively. I've tried all the tweaks I could think of.

Any ideas on how to proceed would be appreciated.

Was it helpful?

Solution

You said it yourself when you said that the exact same command works at the command prompt. The difference there is the presence of a command interpreter, cmd.exe. What that does for you is create the pipe that pipes the input file into the MySQL process.

You have two obvious solutions to the problem:

  1. Use CreateProcess to start the process and set up the pipes yourself. This is a little low level and involves a fair amount of Win32 boilerplate. It does make it a little simpler to block until the process has finished, should you need to do that.
  2. Get ShellExecute to invoke cmd.exe and ask cmd.exe to run MySQL and sort out the pipes.

Option 2 is the simpler. It looks like this:

ShellExecute(
    0, 
    nil, 
    'cmd.exe', 
    '/c mysql --user=root --password=password < C:/directory/filename.sql',
    nil,
    SW_SHOW
);

The /c switch to cmd.exe tells to carry out the command and then terminate – which is just what you want here.

If you need to block your process until the MySQL process is done, then you can switch to ShellExecuteEx. That returns a process handle on which you can wait. Again it's a little harder to operate, but probably still easier than CreateProcess since that forces you to manages the pipe.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top