How to rename a database (table name) command in MySQL

Source: Internet
Author: User
Tags create database


Five ways to change MySQL database name:

The code is as follows Copy Code

1. RENAME DATABASE db_name to New_db_name

This one.. This syntax is added to the MySQL 5.1.7, 5.1.23 and removed.
It is said that it is possible to lose data. It's better not to use it.

It's simple, just a rename. Grammar:

The code is as follows Copy Code

RENAME DATABASE db_name to New_db_name;

# or

RENAME SCHEMA db_name to New_db_name;

This time on the side to do the Web page, is also a learning MySQL


2. If all tables are MyISAM type, you can change the name of the folder
Close Mysqld
Rename the Db_name directory in the data directory to New_db_name
Open mysqld

3. Rename all Tables

The code is as follows Copy Code

CREATE DATABASE New_db_name;
RENAME TABLE Db_name.table1 to New_db_name.table1,
Db_name.table2 to New_db_name.table2;
DROP DATABASE db_name;

4. Mysqldump Export Data and import

The code is as follows Copy Code
mysqldump-uxxxx-pxxxx-h xxxx db_name > Db_name_dump. Sql
Mysql-uxxxx-pxxxx-h xxxx-e "CREATE DATABASE new_db_name"
mysql-uxxxx-pxxxx-h xxxx New_db_name < Db_name_dump. Sql
Mysql-uxxxx-pxxxx-h xxxx-e "DROP DATABASE db_name"

5. Rename all tables using the shell script

The code is as follows Copy Code

#!/bin/bash

mysqlconn= "Mysql-u xxxx-pxxxx-s/var/lib/mysql/mysql.sock-h localhost"
olddb= "Db_name"
newdb= "New_db_name"

# $mysqlconn-E "CREATE DATABASE $newdb"
params=$ ($mysqlconn-N-E "SELECT table_name from INFORMATION_SCHEMA. TABLES WHERE table_schema= ' $olddb ')

for name in $params; Todo
$mysqlconn-E "RENAME TABLE $olddb. $name to $newdb. $name";
Done

# $mysqlconn-E "DROP DATABASE $olddb"

is the optimized version of Method 3.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.