Nice programing

모든 테이블과 필드를 MYSQL의 utf-8-bin 데이터 정렬로 변경하는 스크립트

nicepro 2020. 12. 27. 20:47
반응형

모든 테이블과 필드를 MYSQL의 utf-8-bin 데이터 정렬로 변경하는 스크립트


데이터베이스의 모든 테이블과 필드에서 기본 데이터 정렬을 변경 하는 SQL또는 PHP스크립트를 실행할 수 있습니까?

직접 쓸 수는 있지만 이런 사이트에서 쉽게 구할 수 있어야한다고 생각합니다. 누군가가 하나를 게시하기 전에 내가 직접 만들 수 있다면 내가 직접 게시 할 것입니다.


조심해! 실제로 utf를 다른 인코딩으로 저장하면 손에 엉망이 될 수 있습니다. 먼저 백업하십시오. 그런 다음 몇 가지 표준 방법을 시도하십시오.

예를 들어 http://www.cesspit.net/drupal/node/898 http://www.hackszine.com/blog/archive/2007/05/mysql_database_migration_latin.html

모든 텍스트 필드를 바이너리로 변환 한 다음 다시 varchar / text로 변환해야했습니다. 이것은 내 엉덩이를 구했습니다.

데이터가 UTF8이고 latin1로 저장되었습니다. 제가 한:

인덱스를 삭제합니다. 필드를 바이너리로 변환합니다. utf8-general ci로 변환

LAMP에 있다면 db와 상호 작용하기 전에 set NAMES 명령을 추가하는 것을 잊지 말고 문자 인코딩 헤더를 설정했는지 확인하십시오.


단일 명령으로 수행 할 수 있습니다 (PHP 148 개가 아닌) :

mysql --database=dbname -B -N -e "SHOW TABLES" \
| awk '{print "SET foreign_key_checks = 0; ALTER TABLE", $1, "CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; SET foreign_key_checks = 1; "}' \
| mysql --database=dbname &

명령 줄이 마음에 드셔 야합니다 ... (에 대해 --user--password옵션 을 사용해야 할 수도 있습니다 mysql).

편집 : 외래 키 문제를 방지하기 위해 추가 SET foreign_key_checks = 0;SET foreign_key_checks = 1;


PhpMyAdmin에서 실행하는 두 단계로 쉽게 할 수 있다고 생각합니다.
1 단계:

SELECT CONCAT('ALTER TABLE `', t.`TABLE_SCHEMA`, '`.`', t.`TABLE_NAME`,
 '` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;') as stmt 
FROM `information_schema`.`TABLES` t
WHERE 1
AND t.`TABLE_SCHEMA` = 'database_name'
ORDER BY 1

2 단계 :
이 쿼리는 각 테이블에 대해 하나씩 쿼리 목록을 출력합니다. 쿼리 목록을 복사하여 명령 줄이나 PhpMyAdmin의 SQL 탭에 붙여 넣어 변경해야합니다.


좋아요, 저는이 스레드에서 말한 내용을 고려하여 이것을 작성했습니다. 도움을 주셔서 감사합니다.이 스크립트가 다른 사람들에게 도움이되기를 바랍니다. 사용에 대한 보증이 없으므로 실행하기 전에 백업하십시오. 그것은 해야 모든 데이터베이스 작업; 그리고 그것은 내 스스로 잘 작동했습니다.

편집 : 문자셋 / 컬 레이트를 변환 할 상단에 vars를 추가했습니다. EDIT2 : 데이터베이스 및 테이블의 기본 문자 세트 / 콜레이트를 변경합니다.

<?php

function MysqlError()
{
    if (mysql_errno())
    {
        echo "<b>Mysql Error: " . mysql_error() . "</b>\n";
    }
}

$username = "root";
$password = "";
$db = "database";
$host = "localhost";

$target_charset = "utf8";
$target_collate = "utf8_general_ci";

echo "<pre>";

$conn = mysql_connect($host, $username, $password);
mysql_select_db($db, $conn);

$tabs = array();
$res = mysql_query("SHOW TABLES");
MysqlError();
while (($row = mysql_fetch_row($res)) != null)
{
    $tabs[] = $row[0];
}

// now, fix tables
foreach ($tabs as $tab)
{
    $res = mysql_query("show index from {$tab}");
    MysqlError();
    $indicies = array();

    while (($row = mysql_fetch_array($res)) != null)
    {
        if ($row[2] != "PRIMARY")
        {
            $indicies[] = array("name" => $row[2], "unique" => !($row[1] == "1"), "col" => $row[4]);
            mysql_query("ALTER TABLE {$tab} DROP INDEX {$row[2]}");
            MysqlError();
            echo "Dropped index {$row[2]}. Unique: {$row[1]}\n";
        }
    }

    $res = mysql_query("DESCRIBE {$tab}");
    MysqlError();
    while (($row = mysql_fetch_array($res)) != null)
    {
        $name = $row[0];
        $type = $row[1];
        $set = false;
        if (preg_match("/^varchar\((\d+)\)$/i", $type, $mat))
        {
            $size = $mat[1];
            mysql_query("ALTER TABLE {$tab} MODIFY {$name} VARBINARY({$size})");
            MysqlError();
            mysql_query("ALTER TABLE {$tab} MODIFY {$name} VARCHAR({$size}) CHARACTER SET {$target_charset}");
            MysqlError();
            $set = true;

            echo "Altered field {$name} on {$tab} from type {$type}\n";
        }
        else if (!strcasecmp($type, "CHAR"))
        {
            mysql_query("ALTER TABLE {$tab} MODIFY {$name} BINARY(1)");
            MysqlError();
            mysql_query("ALTER TABLE {$tab} MODIFY {$name} VARCHAR(1) CHARACTER SET {$target_charset}");
            MysqlError();
            $set = true;

            echo "Altered field {$name} on {$tab} from type {$type}\n";
        }
        else if (!strcasecmp($type, "TINYTEXT"))
        {
            mysql_query("ALTER TABLE {$tab} MODIFY {$name} TINYBLOB");
            MysqlError();
            mysql_query("ALTER TABLE {$tab} MODIFY {$name} TINYTEXT CHARACTER SET {$target_charset}");
            MysqlError();
            $set = true;

            echo "Altered field {$name} on {$tab} from type {$type}\n";
        }
        else if (!strcasecmp($type, "MEDIUMTEXT"))
        {
            mysql_query("ALTER TABLE {$tab} MODIFY {$name} MEDIUMBLOB");
            MysqlError();
            mysql_query("ALTER TABLE {$tab} MODIFY {$name} MEDIUMTEXT CHARACTER SET {$target_charset}");
            MysqlError();
            $set = true;

            echo "Altered field {$name} on {$tab} from type {$type}\n";
        }
        else if (!strcasecmp($type, "LONGTEXT"))
        {
            mysql_query("ALTER TABLE {$tab} MODIFY {$name} LONGBLOB");
            MysqlError();
            mysql_query("ALTER TABLE {$tab} MODIFY {$name} LONGTEXT CHARACTER SET {$target_charset}");
            MysqlError();
            $set = true;

            echo "Altered field {$name} on {$tab} from type {$type}\n";
        }
        else if (!strcasecmp($type, "TEXT"))
        {
            mysql_query("ALTER TABLE {$tab} MODIFY {$name} BLOB");
            MysqlError();
            mysql_query("ALTER TABLE {$tab} MODIFY {$name} TEXT CHARACTER SET {$target_charset}");
            MysqlError();
            $set = true;

            echo "Altered field {$name} on {$tab} from type {$type}\n";
        }

        if ($set)
            mysql_query("ALTER TABLE {$tab} MODIFY {$name} COLLATE {$target_collate}");
    }

    // re-build indicies..
    foreach ($indicies as $index)
    {
        if ($index["unique"])
        {
            mysql_query("CREATE UNIQUE INDEX {$index["name"]} ON {$tab} ({$index["col"]})");
            MysqlError();
        }
        else
        {
            mysql_query("CREATE INDEX {$index["name"]} ON {$tab} ({$index["col"]})");
            MysqlError();
        }

        echo "Created index {$index["name"]} on {$tab}. Unique: {$index["unique"]}\n";
    }

    // set default collate
    mysql_query("ALTER TABLE {$tab}  DEFAULT CHARACTER SET {$target_charset} COLLATE {$target_collate}");
}

// set database charset
mysql_query("ALTER DATABASE {$db} DEFAULT CHARACTER SET {$target_charset} COLLATE {$target_collate}");

mysql_close($conn);
echo "</pre>";

?>

이 PHP 스 니펫은 db의 모든 테이블에서 데이터 정렬을 변경합니다. ( 이 사이트 에서 가져온 것입니다 .)

<?php
// your connection
mysql_connect("localhost","root","***");
mysql_select_db("db1");

// convert code
$res = mysql_query("SHOW TABLES");
while ($row = mysql_fetch_array($res))
{
    foreach ($row as $key => $table)
    {
        mysql_query("ALTER TABLE " . $table . " CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci");
        echo $key . " =&gt; " . $table . " CONVERTED<br />";
    }
}
?> 

명령 줄을 사용하는 또 다른 접근 방식은 awk

for t in $(mysql --user=root --password=admin  --database=DBNAME -e "show tables";);do echo "Altering" $t;mysql --user=root --password=admin --database=DBNAME -e "ALTER TABLE $t CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;";done

예쁘다

  for t in $(mysql --user=root --password=admin  --database=DBNAME -e "show tables";);
    do 
       echo "Altering" $t;
       mysql --user=root --password=admin --database=DBNAME -e "ALTER TABLE $t CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;";
    done

위의 스크립트의보다 완전한 버전은 여기에서 찾을 수 있습니다.

http://www.zen-cart.com/index.php?main_page=product_contrib_info&products_id=1937

이 기여에 대한 피드백을 여기에 남겨주세요 : http://www.zen-cart.com/forum/showthread.php?p=1034214


문자셋과 데이터 정렬은 동일하지 않습니다. 데이터 정렬은 문자열 정렬 방법에 대한 일련의 규칙입니다. 문자 집합은 문자를 나타내는 방법에 대한 규칙 집합입니다. 데이터 정렬은 문자 집합에 따라 다릅니다.


변환을 위해 선택된 모든 테이블 위의 스크립트에서 (사용 SHOW TABLES) 테이블을 변환하기 전에 테이블 데이터 정렬을 확인하는 더 편리하고 이식 가능한 방법입니다. 이 쿼리는 다음을 수행합니다.

SELECT table_name
     , table_collation 
FROM information_schema.tables

내 사용자 정의 셸 collatedb를 사용 하면 작동합니다.

collatedb <username> <password> <database> <collation>

예 :

collatedb root 0000 myDatabase utf8_bin

코드에 대해 @nlaq에게 감사드립니다. 아래 솔루션을 시작했습니다.

WordPress가 자동으로 정렬을 설정하지 않는다는 것을 알지 못한 채 WordPress 플러그인을 출시했습니다. 따라서 플러그인을 사용하는 많은 사람들 latin1_swedish_ciutf8_general_ci.

다음은 데이터 latin1_swedish_ci정렬 을 감지 하고으로 변경하기 위해 플러그인에 추가 한 코드 utf8_general_ci입니다.

자신의 플러그인에서 사용하기 전에이 코드를 테스트하십시오!

// list the names of your wordpress plugin database tables (without db prefix)
$tables_to_check = array(
    'social_message',
    'social_facebook',
    'social_facebook_message',
    'social_facebook_page',
    'social_google',
    'social_google_mesage',
    'social_twitter',
    'social_twitter_message',
);
// choose the collate to search for and replace:
$convert_fields_collate_from = 'latin1_swedish_ci';
$convert_fields_collate_to = 'utf8_general_ci';
$convert_tables_character_set_to = 'utf8';
$show_debug_messages = false;
global $wpdb;
$wpdb->show_errors();
foreach($tables_to_check as $table) {
    $table = $wpdb->prefix . $table;
    $indicies = $wpdb->get_results(  "SHOW INDEX FROM `$table`", ARRAY_A );
    $results = $wpdb->get_results( "SHOW FULL COLUMNS FROM `$table`" , ARRAY_A );
    foreach($results as $result){
        if($show_debug_messages)echo "Checking field ".$result['Field'] ." with collat: ".$result['Collation']."\n";
        if(isset($result['Field']) && $result['Field'] && isset($result['Collation']) && $result['Collation'] == $convert_fields_collate_from){
            if($show_debug_messages)echo "Table: $table - Converting field " .$result['Field'] ." - " .$result['Type']." - from $convert_fields_collate_from to $convert_fields_collate_to \n";
            // found a field to convert. check if there's an index on this field.
            // we have to remove index before converting field to binary.
            $is_there_an_index = false;
            foreach($indicies as $index){
                if ( isset($index['Column_name']) && $index['Column_name'] == $result['Field']){
                    // there's an index on this column! store it for adding later on.
                    $is_there_an_index = $index;
                    $wpdb->query( $wpdb->prepare( "ALTER TABLE `%s` DROP INDEX %s", $table, $index['Key_name']) );
                    if($show_debug_messages)echo "Dropped index ".$index['Key_name']." before converting field.. \n";
                    break;
                }
            }
            $set = false;

            if ( preg_match( "/^varchar\((\d+)\)$/i", $result['Type'], $mat ) ) {
                $wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` VARBINARY({$mat[1]})" );
                $wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` VARCHAR({$mat[1]}) CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}" );
                $set = true;
            } else if ( !strcasecmp( $result['Type'], "CHAR" ) ) {
                $wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` BINARY(1)" );
                $wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` VARCHAR(1) CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}" );
                $set = true;
            } else if ( !strcasecmp( $result['Type'], "TINYTEXT" ) ) {
                $wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` TINYBLOB" );
                $wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` TINYTEXT CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}" );
                $set = true;
            } else if ( !strcasecmp( $result['Type'], "MEDIUMTEXT" ) ) {
                $wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` MEDIUMBLOB" );
                $wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` MEDIUMTEXT CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}" );
                $set = true;
            } else if ( !strcasecmp( $result['Type'], "LONGTEXT" ) ) {
                $wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` LONGBLOB" );
                $wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` LONGTEXT CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}" );
                $set = true;
            } else if ( !strcasecmp( $result['Type'], "TEXT" ) ) {
                $wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` BLOB" );
                $wpdb->query( "ALTER TABLE `{$table}` MODIFY `{$result['Field']}` TEXT CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}" );
                $set = true;
            }else{
                if($show_debug_messages)echo "Failed to change field - unsupported type: ".$result['Type']."\n";
            }
            if($set){
                if($show_debug_messages)echo "Altered field success! \n";
                $wpdb->query( "ALTER TABLE `$table` MODIFY {$result['Field']} COLLATE $convert_fields_collate_to" );
            }
            if($is_there_an_index !== false){
                // add the index back.
                if ( !$is_there_an_index["Non_unique"] ) {
                    $wpdb->query( "CREATE UNIQUE INDEX `{$is_there_an_index['Key_name']}` ON `{$table}` ({$is_there_an_index['Column_name']})", $is_there_an_index['Key_name'], $table, $is_there_an_index['Column_name'] );
                } else {
                    $wpdb->query( "CREATE UNIQUE INDEX `{$is_there_an_index['Key_name']}` ON `{$table}` ({$is_there_an_index['Column_name']})", $is_there_an_index['Key_name'], $table, $is_there_an_index['Column_name'] );
                }
            }
        }
    }
    // set default collate
    $wpdb->query( "ALTER TABLE `{$table}` DEFAULT CHARACTER SET {$convert_tables_character_set_to} COLLATE {$convert_fields_collate_to}" );
    if($show_debug_messages)echo "Finished with table $table \n";
}
$wpdb->hide_errors();

IDE의 다중 선택 기능을 사용하는 간단한 (벙어리? :) 솔루션 :

  1. "SHOW TABLES"실행 쿼리 및 복사 결과 열 (테이블 이름).
  2. 시작을 여러 개 선택하고 "ALTER TABLE"을 추가합니다.
  3. 끝을 여러 개 선택하고 "CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;"
  4. 생성 된 쿼리를 실행합니다.

명령 줄 액세스 권한이 없거나 INFORMATION_SCHEMA 편집 권한이없는 경우 phpmyadmin만으로이 작업을 쉽게 수행 할 수있는 방법이 있습니다.

먼저, 여기에있는 다른 많은 답변의 조언을 들어보십시오. 여기에서 문제를 해결할 수 있으므로 백업을 만드십시오. 이제 백업을 백업하십시오. 또한 데이터가 변경되는 것과 다르게 인코딩 된 경우에는 작동하지 않을 수 있습니다.

시작하기 전에 변경해야하는 잘못된 스키마 및 문자 인코딩의 정확한 이름을 찾아야합니다.

  1. 데이터베이스를 SQL로 내 보냅니다. 사본을 만드십시오. 원하는 텍스트 편집기에서 엽니 다.
  2. 먼저 스키마를 찾아 바꾸기 (예 : find : latin1_swedish_ci , replace : utf8_general_ci)
  3. 필요한 경우 문자 인코딩을 찾아서 바꾸 십시오. 예를 들면 다음과 같습니다. find : latin1 , replace : utf8
  4. 새 테스트 데이터베이스를 만들고 새 SQL 파일을 phpmyadmin에 업로드합니다.

이것은 매우 쉬운 방법이지만 데이터의 인코딩을 변경하지 않으므로 특정 상황에서만 작동합니다.


가장 빠른 방법은 콘솔에서 phpmyadmin과 일부 jQuery를 사용하는 것입니다.

테이블의 구조로 이동하여 크롬 / 파이어 폭스 개발자 콘솔 (일반적으로 키보드의 F12)을 엽니 다.

  1. 이 코드를 실행하여 잘못된 문자 집합이있는 모든 필드를 선택하고 수정을 시작합니다.

    var elems = $('dfn'); var lastID = elems.length - 1;
    elems.each(function(i) {
        if ($(this).html() != 'utf8_general_ci') { 
           $('input:checkbox', $('td', $(this).parent().parent()).first()).attr('checked','checked');
        }       
    
        if (i == lastID) {
            $("button[name='submit_mult'][value='change']").click();
        }
    });
    
  2. 페이지가로드 될 때 콘솔에서 다음 코드를 사용하여 올바른 인코딩을 선택하십시오.

    $("select[name*='field_collation']" ).val('utf8_general_ci');
    
  3. 저장

  4. "Operation"탭의 "Collation"필드에서 테이블의 문자 집합을 변경합니다.

phpmyadmin 4.0 및 4.4에서 테스트되었지만 모든 4.x 버전에서 작동한다고 생각합니다.


PHP7에서 작동하고 다중 열 인덱스, 이진 데이터 정렬 (예 :) 등을 올바르게 처리하기 위해 nlaq의 답변을 업데이트 latin1_bin하고 코드를 약간 정리했습니다. 이것은 내 데이터베이스를 latin1에서 utf8로 성공적으로 마이그레이션 한 유일한 코드입니다.

<?php

/////////// BEGIN CONFIG ////////////////////

$username = "";
$password = "";
$db = "";
$host = "";

$target_charset = "utf8";
$target_collation = "utf8_unicode_ci";
$target_bin_collation = "utf8_bin";

///////////  END CONFIG  ////////////////////

function MySQLSafeQuery($conn, $query) {
    $res = mysqli_query($conn, $query);
    if (mysqli_errno($conn)) {
        echo "<b>Mysql Error: " . mysqli_error($conn) . "</b>\n";
        echo "<span>This query caused the above error: <i>" . $query . "</i></span>\n";
    }
    return $res;
}

function binary_typename($type) {
    $mysql_type_to_binary_type_map = array(
        "VARCHAR" => "VARBINARY",
        "CHAR" => "BINARY(1)",
        "TINYTEXT" => "TINYBLOB",
        "MEDIUMTEXT" => "MEDIUMBLOB",
        "LONGTEXT" => "LONGBLOB",
        "TEXT" => "BLOB"
    );

    $typename = "";
    if (preg_match("/^varchar\((\d+)\)$/i", $type, $mat))
        $typename = $mysql_type_to_binary_type_map["VARCHAR"] . "(" . (2*$mat[1]) . ")";
    else if (!strcasecmp($type, "CHAR"))
        $typename = $mysql_type_to_binary_type_map["CHAR"] . "(1)";
    else if (array_key_exists(strtoupper($type), $mysql_type_to_binary_type_map))
        $typename = $mysql_type_to_binary_type_map[strtoupper($type)];
    return $typename;
}

echo "<pre>";

// Connect to database
$conn = mysqli_connect($host, $username, $password);
mysqli_select_db($conn, $db);

// Get list of tables
$tabs = array();
$query = "SHOW TABLES";
$res = MySQLSafeQuery($conn, $query);
while (($row = mysqli_fetch_row($res)) != null)
    $tabs[] = $row[0];

// Now fix tables
foreach ($tabs as $tab) {
    $res = MySQLSafeQuery($conn, "SHOW INDEX FROM `{$tab}`");
    $indicies = array();

    while (($row = mysqli_fetch_array($res)) != null) {
        if ($row[2] != "PRIMARY") {
            $append = true;
            foreach ($indicies as $index) {
                if ($index["name"] == $row[2]) {
                    $index["col"][] = $row[4];
                    $append = false;
                }
            }
            if($append)
                $indicies[] = array("name" => $row[2], "unique" => !($row[1] == "1"), "col" => array($row[4]));
        }
    }

    foreach ($indicies as $index) {
        MySQLSafeQuery($conn, "ALTER TABLE `{$tab}` DROP INDEX `{$index["name"]}`");
        echo "Dropped index {$index["name"]}. Unique: {$index["unique"]}\n";
    }

    $res = MySQLSafeQuery($conn, "SHOW FULL COLUMNS FROM `{$tab}`");
    while (($row = mysqli_fetch_array($res)) != null) {
        $name = $row[0];
        $type = $row[1];
        $current_collation = $row[2];
        $target_collation_bak = $target_collation;
        if(!strcasecmp($current_collation, "latin1_bin"))
            $target_collation = $target_bin_collation;
        $set = false;
        $binary_typename = binary_typename($type);
        if ($binary_typename != "") {
            MySQLSafeQuery($conn, "ALTER TABLE `{$tab}` MODIFY `{$name}` {$binary_typename}");
            MySQLSafeQuery($conn, "ALTER TABLE `{$tab}` MODIFY `{$name}` {$type} CHARACTER SET '{$target_charset}' COLLATE '{$target_collation}'");
            $set = true;
            echo "Altered field {$name} on {$tab} from type {$type}\n";
        }
        $target_collation = $target_collation_bak;
    }

    // Rebuild indicies
    foreach ($indicies as $index) {
         // Handle multi-column indices
         $joined_col_str = "";
         foreach ($index["col"] as $col)
             $joined_col_str = $joined_col_str . ", `" . $col . "`";
         $joined_col_str = substr($joined_col_str, 2);

         $query = "";
         if ($index["unique"])
             $query = "CREATE UNIQUE INDEX `{$index["name"]}` ON `{$tab}` ({$joined_col_str})";
         else
             $query = "CREATE INDEX `{$index["name"]}` ON `{$tab}` ({$joined_col_str})";
         MySQLSafeQuery($conn, $query);

        echo "Created index {$index["name"]} on {$tab}. Unique: {$index["unique"]}\n";
    }

    // Set default character set and collation for table
    MySQLSafeQuery($conn, "ALTER TABLE `{$tab}`  DEFAULT CHARACTER SET '{$target_charset}' COLLATE '{$target_collation}'");
}

// Set default character set and collation for database
MySQLSafeQuery($conn, "ALTER DATABASE `{$db}` DEFAULT CHARACTER SET '{$target_charset}' COLLATE '{$target_collation}'");

mysqli_close($conn);
echo "</pre>";

?>

Windows 사용자의 경우

@davidwinterbottom 답변 외에도 Windows 사용자는 아래 명령을 사용할 수 있습니다.

mysql.exe --database=[database] -u [user] -p[password] -B -N -e "SHOW TABLES" \
| awk.exe '{print "SET foreign_key_checks = 0; ALTER TABLE", $1, "CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; SET foreign_key_checks = 1; "}' \
| mysql.exe -u [user] -p[password] --database=[database] &

[database], [user] 및 [password] 자리 표시자를 실제 값으로 바꿉니다.

Git-bash 사용자는이 bash 스크립트를 다운로드 하여 쉽게 실행할 수 있습니다.

참조 URL : https://stackoverflow.com/questions/105572/a-script-to-change-all-tables-and-fields-to-the-utf-8-bin-collation-in-mysql

반응형