mysqlpowershellcmdcharacter-encodingdbforge

Character encoding problem when importing SQL with DBForge and PowerShell into MySQL


I have a problem with MySQL and/or DBforge.

I would like to import a schema using an .sql file that DBforge generated for me by comparing 2 databases.

The file DBforge created for me contains characters with accents (éèêàâ...), so far nothing abnormal, I'm French and the stored procedures I need to import are written in French.

However, when I want to execute this .sql file in my database in a PowerShell :

Get-Content $SQLfile -Encoding UTF8 | 
     mysql --password=$($target.password) -h $($target.host) -P $($target.port) -u $($target.user) --default-character-set utf8mb4 -f -D $db 2> $tempErrorFile

All special characters are replaced by ? despite the fact that my .sql file is in UTF8 and has accents.

Here's my call to dbforge to generate the .sql file for me (although I doubt that's where the problem is):

&$($DBFORGE_PATH + 'dbforgemysql.com') /schemacompare /source connection:$SOURCE_LINE /target connection:$TARGET_LINE /ExcludeComments:Yes /ExcludeDependencies:Yes /IncludeUseDatabase:Yes /filter:$selectedFilter /sync:$SQL_DBFORGE /log:$LOG_DBFORGE_FILE

Here is my call to mysql with the file generated by dbforge :

&cmd /c "mysql --password=$($target.password) -h $($target.host) -P $($target.port) -u $($target.user) --default-character-set=utf8mb4 -f -D $db < $SQLfile 2> $tempErrorFile"

I tried another way:

Get-Content $SQLfile -Encoding UTF8 | 
    mysql --password=$($target.password) -h $($target.host) -P $($target.port) -u $($target.user) --default-character-set=utf8mb4 -f -D $db 2> $tempErrorFile

Solution

  • tl;dr


    Background information:

    Your problem isn't specific to the CLI you're using (mysql), it is rooted in a fundamental PowerShell behavior:

    When PowerShell sends data to an external (native) program via the pipeline, it uses the character encoding stored in the $OutputEncoding preference variable.

    When PowerShell receives data from external programs (via their stdout and stderr streams), PowerShell uses the encoding stored in [Console]::OutputEncoding to decode the data (into .NET strings).


    [1] Except if you've configured your system to use UTF-8 system-wide, but note that doing so has far-reaching consequences - see this answer.