¿Cómo cambiar la intercalación de la base de datos, tabla, columna?


Ahora la base de datos es latin1_general_ci y quiero cambiar la intercalación a utf8_general_ci. ¿Hay alguna configuración en phpMyAdmin para cambiar la intercalación de la base de datos, tabla, columna? En lugar de cambiar uno por uno?

Author: Benjamin, 2009-08-18

15 answers

Necesita convertir cada tabla individualmente:

ALTER TABLE mytable CONVERT TO CHARACTER SET utf8 

(esto también convertirá las columnas), o exportar la base de datos con latin1 e importarla de nuevo con utf8.

 209
Author: Quassnoi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-18 14:14:28

Estoy contribuyendo aquí, como el OP pidió:

¿Cómo cambiar la intercalación de la base de datos, tabla, columna?

La respuesta seleccionada solo la indica a nivel de tabla.


Cambiando la base de datos:

ALTER DATABASE <database_name> CHARACTER SET utf8 COLLATE utf8_unicode_ci;

Cambiándolo por tabla:

ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;

Una buena práctica es cambiarlo a nivel de tabla, ya que también lo cambiará para las columnas. Cambiar para una columna específica es para cualquier caso específico.

Cambiando la intercalación para un columna:

ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci;
 89
Author: Nabeel Ahmed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-17 11:51:05

Puede ejecutar un script php.

               <?php
                   $con = mysql_connect('localhost','user','password');
                   if(!$con) { echo "Cannot connect to the database ";die();}
                   mysql_select_db('dbname');
                   $result=mysql_query('show tables');
                   while($tables = mysql_fetch_array($result)) {
                            foreach ($tables as $key => $value) {
                             mysql_query("ALTER TABLE $value CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
                       }}
                   echo "The collation of your database has been successfully changed!";
                ?>
 61
Author: hkasera,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-04 11:22:56

Para cambiar la intercalación de tablas individualmente puede usar,

ALTER TABLE mytable CONVERT TO CHARACTER SET utf8

Para establecer la intercalación predeterminada para toda la base de datos,

ALTER DATABASE  `databasename` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin

O bien

Goto PhpMyAdmin->Operaciones>Intercalación.

Allí encontrará el cuadro de selección que contiene todas las intercalaciones existentes. Así que aquí puedes cambiar tu cotejo. Así que aquí después de la tabla de la base de datos seguirá esta intercalación mientras crea una nueva columna . No es necesario seleccionar intercalación mientras se crea una nueva columna.

 34
Author: jeeva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-16 08:05:49

Puede establecer la intercalación predeterminada en varios niveles:

Http://dev.mysql.com/doc/refman/5.0/en/charset-syntax.html

1) cliente 2) por defecto del servidor 3) base de datos por defecto 4) tabla predeterminada 5) columna

 9
Author: andersonbd1,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-18 14:15:24

Si ejecuta phpMyAdmin > > seleccionar base de datos > > seleccionar tabla > > vaya a la pestaña "Operaciones" > > en la sección "Opciones de tabla" > > puede elegir la intercalación de la lista desplegable >> y una vez que presione {Go} en la parte superior de la pantalla verá un mensaje:

Su consulta SQL se ha ejecutado correctamente

Y un script

ALTER TABLE `tableName` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci 

Pero NO cambiará las intercalaciones de columnas existentes. Para ello puede utilizar este script (este también vino de phpMyAdmin)

ALTER TABLE  `tableName` CHANGE  `Name`  `Name` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL
 9
Author: Yevgeniy Afanasyev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-04 04:44:59

La siguiente consulta generará consultas ALTER que cambian la intercalación de todas las columnas apropiadas en todas las tablas a un tipo determinado (utf8_general_ci en mi ejemplo a continuación).

SELECT concat
        (
            'ALTER TABLE ', 
                t1.TABLE_SCHEMA, 
                '.', 
                t1.table_name, 
                ' MODIFY ', 
                t1.column_name, 
                ' ', 
                t1.data_type, 
                '(' , 
                    CHARACTER_MAXIMUM_LENGTH, 
                ')', 
                ' CHARACTER SET utf8 COLLATE utf8_general_ci;'
        )
from 
    information_schema.columns t1
where 
    t1.TABLE_SCHEMA like 'you_db_name_goes_here' AND
    t1.COLLATION_NAME IS NOT NULL AND
    t1.COLLATION_NAME NOT IN ('utf8_general_ci');
 6
Author: Parampal Pooni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-14 01:26:29

Me sorprendió saber, y así tuve que volver aquí e informar, que el excelente y bien mantenido Interconnect/it SAFE SEARCH AND REPLACE ON DATABASE script tiene algunas opciones para convertir tablas a utf8 / unicode, e incluso para convertir a innodb. Es un script comúnmente utilizado para migrar un sitio web basado en bases de datos (Wordpress, Drupal, Joomla, etc.) de un dominio a otro.

botones de script de interconexión

 4
Author: Adam Nofsinger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-19 20:10:52

Puede cambiar el CONJUNTO de CARACTERES y la INTERCALACIÓN de todas sus tablas a través del script PHP de la siguiente manera. Me gusta la respuesta de hkasera, pero el problema es que la consulta se ejecuta dos veces en cada tabla. Este código es casi el mismo excepto el uso de MySqli en lugar de mysql y la prevención de la doble consulta. Si pudiera votar, habría votado la respuesta de Hkasera.

<?php
$conn1=new MySQLi("localhost","user","password","database");
if($conn1->connect_errno){
    echo mysqli_connect_error();
    exit;
}
$res=$conn1->query("show tables") or die($conn1->error);
while($tables=$res->fetch_array()){
    $conn1->query("ALTER TABLE $tables[0] CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci") or die($conn1->error);
}
echo "The collation of your database has been successfully changed!";

$res->free();
$conn1->close();

?>
 3
Author: mtmehdi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-02 05:36:55

Lo leí aquí, que necesita convertir cada tabla manualmente, no es cierto. Aquí hay una solución de cómo hacerlo con un procedimiento almacenado:

DELIMITER $$

DROP PROCEDURE IF EXISTS changeCollation$$

-- character_set parameter could be 'utf8'
-- or 'latin1' or any other valid character set
CREATE PROCEDURE changeCollation(IN character_set VARCHAR(255))
BEGIN
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE v_table_name varchar(255) DEFAULT "";
DECLARE v_message varchar(4000) DEFAULT "No records";

-- This will create a cursor that selects each table,
-- where the character set is not the one
-- that is defined in the parameter

DECLARE alter_cursor CURSOR FOR SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE()
AND COLLATION_NAME NOT LIKE CONCAT(character_set, '_%');

-- This handler will set the value v_finished to 1
-- if there are no more rows

DECLARE CONTINUE HANDLER
FOR NOT FOUND SET v_finished = 1;

OPEN alter_cursor;

-- Start a loop to fetch each rows from the cursor
get_table: LOOP

-- Fetch the table names one by one
FETCH alter_cursor INTO v_table_name;

-- If there is no more record, then we have to skip
-- the commands inside the loop
IF v_finished = 1 THEN
LEAVE get_table;
END IF;

IF v_table_name != '' THEN

IF v_message = 'No records' THEN
SET v_message = '';
END IF;

-- This technic makes the trick, it prepares a statement
-- that is based on the v_table_name parameter and it means
-- that this one is different by each iteration inside the loop

SET @s = CONCAT('ALTER TABLE ',v_table_name,
' CONVERT TO CHARACTER SET ', character_set);
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET v_message = CONCAT('The table ', v_table_name ,
' was changed to the default collation of ', character_set,
'.\n', v_message);

SET v_table_name = '';

END IF;
-- Close the loop and the cursor
END LOOP get_table;
CLOSE alter_cursor;

-- Returns information about the altered tables or 'No records'
SELECT v_message;

END $$

DELIMITER ;

Después de crear el procedimiento llámelo simplemente:

CALL changeCollation('utf8’);

Para más detalles lea este blog .

 3
Author: András Ottó,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-09 13:07:05

Simplemente puede agregar este código al archivo de script

//Database Connection
$host = 'localhost';
$db_name = 'your_database_name';
$db_user =  'your_database_user_name';
$db_pass = 'your_database_user_password';

$con = mysql_connect($host,$db_user,$db_pass);

if(!$con) { echo "Cannot connect to the database ";die();}

  mysql_select_db($db_name);

  $result=mysql_query('show tables');

  while($tables = mysql_fetch_array($result)) {
    foreach ($tables as $key => $value) {
    mysql_query("ALTER TABLE $value CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
  }
}

echo "The collation of your database has been successfully changed!";
 3
Author: Chandra Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-05 11:41:32

Si desea actualizar el conjunto de caracteres predeterminado en un esquema:

 ALTER SCHEMA MYSCHEMA DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_unicode_ci;
 2
Author: Mircea Stanciu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-31 03:44:57

Usé el siguiente script de shell. Toma el nombre de la base de datos como parámetro y convierte todas las tablas en otro conjunto de caracteres y la intercalación (dada por otros parámetros o valor predeterminado definido en el script).

#!/bin/bash

# mycollate.sh <database> [<charset> <collation>]
# changes MySQL/MariaDB charset and collation for one database - all tables and
# all columns in all tables

DB="$1"
CHARSET="$2"
COLL="$3"

[ -n "$DB" ] || exit 1
[ -n "$CHARSET" ] || CHARSET="utf8mb4"
[ -n "$COLL" ] || COLL="utf8mb4_general_ci"

echo $DB
echo "ALTER DATABASE $DB CHARACTER SET $CHARSET COLLATE $COLL;" | mysql

echo "USE $DB; SHOW TABLES;" | mysql -s | (
    while read TABLE; do
        echo $DB.$TABLE
        echo "ALTER TABLE $TABLE CONVERT TO CHARACTER SET $CHARSET COLLATE $COLL;" | mysql $DB
    done
)
 1
Author: Petr Stastny,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-11 10:52:12

Quick way - exporte al archivo SQL, use buscar y reemplazar para cambiar el texto que necesita cambiar. Cree una nueva base de datos, importe los datos y luego cambie el nombre de la base de datos antigua y la nueva al nombre anterior.

 0
Author: kickoff3pm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-09 14:25:00

Simplemente ejecute este SQL. Cambie su INTERCALACIÓN a lo que necesita y DatabaseName.

SELECT CONCAT("ALTER TABLE ", TABLE_SCHEMA, '.', TABLE_NAME," COLLATE utf8_general_ci;") AS    ExecuteTheString
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="databaseName"
AND TABLE_TYPE="BASE TABLE";
 0
Author: Dzintars,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-23 15:13:18