0
mysql -u username -p"password" DbName -h host.com.us < inputFile.sql > outputFile.csv

I'm using the above command to run a query that will output the file locally. The file is only delimited by tabs. I have seen several answers that use shell command and I need formatting commands for Windows command prompt.

2

1 Answer 1

1

The following command should do what you want at a PowerShell command prompt on Windows:

Get-Content inputFile.sql | mysql -u username -p'password' DbName -h host.com.us | ForEach-Object { $_ -replace "\t","," } | Out-File outputFile.csv

Note that I've written the above out using the full names of the PowerShell cmdlets for clarity. One would typically use the aliases gc and % for Get-Content and ForEach-Object respectively.

A wrinkle that often catches me is that PowerShell uses a 16-bit Unicode encoding by default, so the outputFile.csv produced by the above example command line will be 16-bit Unicode. The Out-File cmdlet has an -Encoding parameter to allow you to make a different choice, such as UTF8. The above command could be rewritten as:

gc inputFile.sql | mysql -u username -p'password' dbName -h host.com.us | % { $_ -replace "\t","," } | Out-File -Encoding utf8 outputFile.csv

Edit: Changed password delimiters to single quotes to prevent PowerShell from attempting string interpolations.

Sign up to request clarification or add additional context in comments.

8 Comments

"The splatting operator '@' cannot be used to reference variables in an expression. '@S2d' can be used only as an argume nt to a command. To reference variables in an expression use '$S2d'."
@user3704920 I need a little more context to understand your comment
my apologies. It's not recognizing the connection password as a string. Sees the characters as commands.
Ah, likewise apologies - if you enclose the password in single quotes 'thus' instead of double quotes ("not like this") then PowerShell shouldn't interfere with it - I'll edit my answer accordingly.
same issue with single quotes. Odd. gc '/Users/first.last/Desktop/queryHere.sql' | mysql -u 'first.last' -p'KS2d&0j89j(@&jSjsJ!' DBName -h host.com.co.uk | % { $_ -replace "\t","," } | Out-File -Encoding utf8 '/Users/first.last/Desktop/myfile.csv'
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.