MySQL 데이터베이스 이름 바꾸기
이 질문에 이미 답변이 있습니다.
이름으로 데이터베이스를 만들었습니다 hrms. 이제 데이터베이스 이름을 sunhrm. 그러나 MySQL 워크 벤치에서는 비활성화되어 있습니다. Linux 서버 자체에서 할 수 있습니까?
나는 당신이 이것을 할 수 있다고 생각하지 않습니다. 해당 데이터베이스를 덤프하고 새로 명명 된 데이터베이스를 만든 다음 덤프를 가져와야한다고 생각합니다.
이것이 라이브 시스템 인 경우 다운해야합니다. 할 수없는 경우이 데이터베이스에서 새 데이터베이스로 복제를 설정해야합니다.
이 작업을 수행하는 명령을 보려면 @jan에 세부 정보가 있습니다.
명령 줄에서이 작업을 수행해야하는 경우 다음 코드를 복사, 수정 및 붙여 넣기 만하면됩니다.
mysql -e "CREATE DATABASE \`new_database\`;"
for table in `mysql -B -N -e "SHOW TABLES;" old_database`
do
mysql -e "RENAME TABLE \`old_database\`.\`$table\` to \`new_database\`.\`$table\`"
done
mysql -e "DROP DATABASE \`old_database\`;"
덤프를 파일에 저장하지 않고 mysqldump 명령을 통해 데이터베이스를 복사 할 수 있습니다.
mysql -u root -p -e "create database my_new_database"mysqldump -u root -p original_database | mysql -u root -p my_new_databasemysql -u root -p -e "drop database original_database"
이전 데이터베이스가 존재했던 그대로 새 데이터베이스를 만든 다음 완료되면 이전 데이터베이스를 삭제할 수 있습니다. mysqldump 도구를 사용하여 데이터베이스의 .sql 백업을 만들 mysqldump orig_db > orig_db.sql거나 사용자 이름과 암호를 사용해야하는 경우 mysqldump -u root -p orig_db > orig_db.sql. orig_db는 "이름 변경"하려는 데이터베이스의 이름이고, root는 로그인하는 사용자이며 orig_db.sql은 백업을 포함하여 생성 된 파일입니다. 이제 원하는 데이터베이스 이름으로 비어있는 새 데이터베이스를 만듭니다. 예 : mysql -u root -p -e "create database new_db". 완료되면 mysql -u root -p new_db < orig_db.sql. new_db는 이제 orig_db의 완벽한 복사본으로 존재합니다. 그런 다음 원래 데이터베이스를 원하는 데이터베이스 이름으로 새 데이터베이스에 기존 데이터베이스로 삭제할 수 있습니다.
위의 모든 설명이없는 간단하고 빠른 단계는 다음과 같습니다.
mysqldump -u root -p original_database > original_database.sqlmysql -u root -p -e "create database my_new_database"mysql -u root -p my_new_database < original_database.sqlmysql -u root -p -e drop database originl_database
이것이 도움이되기를 바라며 이것은 데이터를 손상시키고 불일치를 생성하는 임시 방법을 사용하지 않고이를 달성 할 수있는 신뢰할 수있는 방법입니다.
새 스키마 "other_db"를 생성 한 후 "current_db"의 각 테이블에 대해 RENAME 문으로 수행 할 수 있습니다.
RENAME TABLE current_db.tbl_name TO other_db.tbl_name
두 가지 방법이 있습니다.
방법 1 : 데이터베이스 스키마 이름을 변경하는 잘 알려진 방법은 Mysqldump를 사용하여 스키마를 덤프하고 다른 스키마에서 복원 한 다음 필요한 경우 이전 스키마를 삭제하는 것입니다.
에서 Shell
mysqldump emp > emp.out
mysql -e "CREATE DATABASE employees;"
mysql employees < emp.out
mysql -e "DROP DATABASE emp;"
위의 방법은 쉽지만 시간과 공간이 많이 소요됩니다. 스키마가 100GB 이상이면 어떻게 됩니까? 위의 명령을 함께 파이프하여 공간을 절약 할 수있는 방법이 있지만 시간을 절약하지는 못합니다.
이러한 상황을 해결하려면 스키마 이름을 바꾸는 또 다른 빠른 방법이 있지만이를 수행하는 동안주의해야합니다.
방법 2 : MySQL은 다른 스키마에서도 작동하는 테이블 이름을 바꾸는 데 아주 좋은 기능을 가지고 있습니다. 이 이름 변경 작업은 원자 적이며 이름이 변경되는 동안 다른 사람은 테이블에 액세스 할 수 없습니다. 테이블 이름이나 스키마 변경은 메타 데이터 변경 일 뿐이므로 완료하는 데 시간이 조금 걸립니다. 이름 바꾸기를 수행하는 절차 적 접근 방식은 다음과 같습니다.
- 원하는 이름으로 새 데이터베이스 스키마를 만듭니다.
- MySQL의 "RENAME TABLE"명령을 사용하여 이전 스키마에서 새 스키마로 테이블 이름을 바꿉니다.
- 이전 데이터베이스 스키마를 삭제하십시오.
이 경우 views, triggers, functions, stored procedures스키마에, 그 역시 다시 작성해야합니다. 테이블에 트리거가 있으면 MySQL의 "RENAME TABLE"이 실패합니다. 이를 해결하기 위해 다음을 수행 할 수 있습니다.
1) Dump the triggers, events and stored routines in a separate file. mysqldump 명령에 -E, -R 플래그 (트리거를 덤프하는 -t -d와 함께)를 사용하여 수행했습니다. 트리거가 덤프되면 RENAME TABLE 명령이 작동하려면 스키마에서 트리거를 삭제해야합니다.
$ mysqldump <old_schema_name> -d -t -R -E > stored_routines_triggers_events.out
2) "BASE"테이블 목록 만 생성합니다. information_schema.TABLES 테이블에 대한 쿼리를 사용하여 찾을 수 있습니다.
mysql> select TABLE_NAME from information_schema.tables where
table_schema='<old_schema_name>' and TABLE_TYPE='BASE TABLE';
3) 아웃 파일에서 뷰를 덤프합니다. 동일한 information_schema.TABLES 테이블에 대한 쿼리를 사용하여보기를 찾을 수 있습니다.
mysql> select TABLE_NAME from information_schema.tables where
table_schema='<old_schema_name>' and TABLE_TYPE='VIEW';
$ mysqldump <database> <view1> <view2> … > views.out
4) old_schema의 현재 테이블에서 트리거를 삭제합니다.
mysql> DROP TRIGGER <trigger_name>;
...
5) Restore the above dump files once all the “Base” tables found in step #2 are renamed.
mysql> RENAME TABLE <old_schema>.table_name TO <new_schema>.table_name;
...
$ mysql <new_schema> < views.out
$ mysql <new_schema> < stored_routines_triggers_events.out
Intricacies with above methods : We may need to update the GRANTS for users such that they match the correct schema_name. These could fixed with a simple UPDATE on mysql.columns_priv, mysql.procs_priv, mysql.tables_priv, mysql.db tables updating the old_schema name to new_schema and calling “Flush privileges;”. Although “method 2″ seems a bit more complicated than the “method 1″, this is totally scriptable. A simple bash script to carry out the above steps in proper sequence, can help you save space and time while renaming database schemas next time.
The Percona Remote DBA team have written a script called “rename_db” that works in the following way :
[root@dba~]# /tmp/rename_db
rename_db <server> <database> <new_database>
To demonstrate the use of this script, used a sample schema “emp”, created test triggers, stored routines on that schema. Will try to rename the database schema using the script, which takes some seconds to complete as opposed to time consuming dump/restore method.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| emp |
| mysql |
| performance_schema |
| test |
+--------------------+
[root@dba ~]# time /tmp/rename_db localhost emp emp_test
create database emp_test DEFAULT CHARACTER SET latin1
drop trigger salary_trigger
rename table emp.__emp_new to emp_test.__emp_new
rename table emp._emp_new to emp_test._emp_new
rename table emp.departments to emp_test.departments
rename table emp.dept to emp_test.dept
rename table emp.dept_emp to emp_test.dept_emp
rename table emp.dept_manager to emp_test.dept_manager
rename table emp.emp to emp_test.emp
rename table emp.employees to emp_test.employees
rename table emp.salaries_temp to emp_test.salaries_temp
rename table emp.titles to emp_test.titles
loading views
loading triggers, routines and events
Dropping database emp
real 0m0.643s
user 0m0.053s
sys 0m0.131s
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| emp_test |
| mysql |
| performance_schema |
| test |
+--------------------+
As you can see in the above output the database schema “emp” was renamed to “emp_test” in less than a second. Lastly, This is the script from Percona that is used above for “method 2″.
#!/bin/bash
# Copyright 2013 Percona LLC and/or its affiliates
set -e
if [ -z "$3" ]; then
echo "rename_db <server> <database> <new_database>"
exit 1
fi
db_exists=`mysql -h $1 -e "show databases like '$3'" -sss`
if [ -n "$db_exists" ]; then
echo "ERROR: New database already exists $3"
exit 1
fi
TIMESTAMP=`date +%s`
character_set=`mysql -h $1 -e "show create database $2\G" -sss | grep ^Create | awk -F'CHARACTER SET ' '{print $2}' | awk '{print $1}'`
TABLES=`mysql -h $1 -e "select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='BASE TABLE'" -sss`
STATUS=$?
if [ "$STATUS" != 0 ] || [ -z "$TABLES" ]; then
echo "Error retrieving tables from $2"
exit 1
fi
echo "create database $3 DEFAULT CHARACTER SET $character_set"
mysql -h $1 -e "create database $3 DEFAULT CHARACTER SET $character_set"
TRIGGERS=`mysql -h $1 $2 -e "show triggers\G" | grep Trigger: | awk '{print $2}'`
VIEWS=`mysql -h $1 -e "select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='VIEW'" -sss`
if [ -n "$VIEWS" ]; then
mysqldump -h $1 $2 $VIEWS > /tmp/${2}_views${TIMESTAMP}.dump
fi
mysqldump -h $1 $2 -d -t -R -E > /tmp/${2}_triggers${TIMESTAMP}.dump
for TRIGGER in $TRIGGERS; do
echo "drop trigger $TRIGGER"
mysql -h $1 $2 -e "drop trigger $TRIGGER"
done
for TABLE in $TABLES; do
echo "rename table $2.$TABLE to $3.$TABLE"
mysql -h $1 $2 -e "SET FOREIGN_KEY_CHECKS=0; rename table $2.$TABLE to $3.$TABLE"
done
if [ -n "$VIEWS" ]; then
echo "loading views"
mysql -h $1 $3 < /tmp/${2}_views${TIMESTAMP}.dump
fi
echo "loading triggers, routines and events"
mysql -h $1 $3 < /tmp/${2}_triggers${TIMESTAMP}.dump
TABLES=`mysql -h $1 -e "select TABLE_NAME from information_schema.tables where table_schema='$2' and TABLE_TYPE='BASE TABLE'" -sss`
if [ -z "$TABLES" ]; then
echo "Dropping database $2"
mysql -h $1 $2 -e "drop database $2"
fi
if [ `mysql -h $1 -e "select count(*) from mysql.columns_priv where db='$2'" -sss` -gt 0 ]; then
COLUMNS_PRIV=" UPDATE mysql.columns_priv set db='$3' WHERE db='$2';"
fi
if [ `mysql -h $1 -e "select count(*) from mysql.procs_priv where db='$2'" -sss` -gt 0 ]; then
PROCS_PRIV=" UPDATE mysql.procs_priv set db='$3' WHERE db='$2';"
fi
if [ `mysql -h $1 -e "select count(*) from mysql.tables_priv where db='$2'" -sss` -gt 0 ]; then
TABLES_PRIV=" UPDATE mysql.tables_priv set db='$3' WHERE db='$2';"
fi
if [ `mysql -h $1 -e "select count(*) from mysql.db where db='$2'" -sss` -gt 0 ]; then
DB_PRIV=" UPDATE mysql.db set db='$3' WHERE db='$2';"
fi
if [ -n "$COLUMNS_PRIV" ] || [ -n "$PROCS_PRIV" ] || [ -n "$TABLES_PRIV" ] || [ -n "$DB_PRIV" ]; then
echo "IF YOU WANT TO RENAME the GRANTS YOU NEED TO RUN ALL OUTPUT BELOW:"
if [ -n "$COLUMNS_PRIV" ]; then echo "$COLUMNS_PRIV"; fi
if [ -n "$PROCS_PRIV" ]; then echo "$PROCS_PRIV"; fi
if [ -n "$TABLES_PRIV" ]; then echo "$TABLES_PRIV"; fi
if [ -n "$DB_PRIV" ]; then echo "$DB_PRIV"; fi
echo " flush privileges;"
fi
In short no. It is generally thought to be too dangerous to rename a database. MySQL had that feature for a bit, but it was removed. You would be better off using the workbench to export both the schema and data to SQL then changing the CREATE DATABASE name there before you run/import it.
For impatient mysql users (like me), the solution is:
/etc/init.d/mysql stop
mv /var/lib/mysql/old_database /var/lib/mysql/new_database
/etc/init.d/mysql start
I used following method to rename the database
take backup of the file using mysqldump or any DB tool eg heidiSQL,mysql administrator etc
Open back up (eg backupfile.sql) file in some text editor.
Search and replace the database name and save file.
Restore the edited SQL file
If your DB contains only MyISAM tables (do not use this method if you have InnoDB tables):
- shut down the MySQL server
- go to the mysql
datadirectory and rename the database directory (Note: non-alpha characters need to be encoded in a special way) - restart the server
- adjust privileges if needed (grant access to the new DB name)
You can script it all in one command so that downtime is just a second or two.
First backup the old database called HRMS and edit the script file with replace the word HRMS to SUNHRM. After this step import the database file to the mysql
Another way to rename the database or taking image of the database is by using Reverse engineering option in the database tab. It will create a ERR diagram for the database. Rename the schema there.
after that go to file menu and go to export and forward engineer the database.
Then you can import the database.
참고URL : https://stackoverflow.com/questions/12190000/rename-mysql-database
'IT박스' 카테고리의 다른 글
| MySQL에 Python datetime.datetime 객체 삽입 (0) | 2020.08.09 |
|---|---|
| Javascript는 연중 일을 계산합니다 (1-366). (0) | 2020.08.09 |
| Java 8이 값이나 기능을 반복하는 좋은 방법을 제공합니까? (0) | 2020.08.09 |
| JavaScript에서 regex \ S는 무엇을 의미합니까? (0) | 2020.08.09 |
| Java에서 기본 요소에 대한 참조에 의한 전달과 동등한 작업을 수행하는 방법 (0) | 2020.08.09 |