A script to change all tables and fields to the utf-8-bin collation in MYSQL

后端 未结 16 918
有刺的猬
有刺的猬 2020-12-04 06:24

Is there a SQL or PHP script that I can run that will change the default collation in all tables and fields in a database?

I can write one

相关标签:
16条回答
  • 2020-12-04 07:04

    For Windows Users

    In addition to @davidwinterbottom answer, windows users can use command below:

    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] &
    

    Replace [database], [user] and [password] placeholders with actual values.

    Git-bash users can download this bash script and run it easily.

    0 讨论(0)
  • 2020-12-04 07:11

    I think the fastest way is with phpmyadmin and some jQuery on console.

    Go to table's structure and open chrome/firefox developer console (normally F12 on keyboard):

    1. run this code to select all fields with incorrect charset and start modify:

      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. when page is loaded use this code on console to select correct encoding:

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

    4. change the table's charset on "Collation" field on "Operation" tab

    Tested on phpmyadmin 4.0 and 4.4, but I think work on all 4.x versions

    0 讨论(0)
  • 2020-12-04 07:12

    Be careful! If you actually have utf stored as another encoding, you could have a real mess on your hands. Back up first. Then try some of the standard methods:

    for instance http://www.cesspit.net/drupal/node/898 http://www.hackszine.com/blog/archive/2007/05/mysql_database_migration_latin.html

    I've had to resort to converting all text fields to binary, then back to varchar/text. This has saved my ass.

    I had data is UTF8, stored as latin1. What I did:

    Drop indexes. Convert fields to binary. Convert to utf8-general ci

    If your on LAMP, don’t forget to add set NAMES command before interacting with the db, and make sure you set character encoding headers.

    0 讨论(0)
  • 2020-12-04 07:12

    Use my custom shell collatedb, it should work :

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

    Example :

    collatedb root 0000 myDatabase utf8_bin
    
    0 讨论(0)
提交回复
热议问题