MySQL - 重命名表



在关系数据库中,用户和数据库管理员可能都需要更改表名以使其更适合特定情况。

MySQL 提供两种不同的方法来重命名 MySQL 表。我们可以使用 **RENAME TABLE** 或 **ALTER TABLE** 语句。在本教程中,我们将通过合适的示例来理解它们。

MySQL RENAME TABLE 语句

MySQL RENAME TABLE 语句用于将数据库中现有表的名称更改为另一个名称。

语法

以下是 MySQL RENAME TABLE 语句的基本语法:

RENAME TABLE table_name TO new_name;

其中,table_name 是现有表的名称,new_name 是您要分配的新名称。

示例

让我们首先使用 CREATE 语句在 MySQL 数据库中创建一个名为 **CUSTOMERS** 的表,如下所示:

CREATE TABLE CUSTOMERS ( ID INT, NAME VARCHAR(20), AGE INT );

在这里,我们使用以下查询将上面创建的 CUSTOMERS 表重命名为 **BUYERS**:

RENAME TABLE CUSTOMERS to BUYERS;

输出

表已重命名,没有任何错误。

Query OK, 0 rows affected (0.01 sec)

验证

执行以下查询以检索 CUSTOMERS 表的描述:

DESC CUSTOMERS;

它将显示错误,因为我们已将 CUSTOMERS 表的名称更改为 BUYERS,并且我们的数据库中不存在 CUSTOMERS 表。

ERROR 1146 (42S02): Table 'tutorials.customers' doesn't exist

重命名多个表

使用 MySQL RENAME TABLE 语句,我们还可以用单个查询重命名多个表。

语法

以下是使用 MySQL RENAME TABLE 语句重命名多个表的语法:

RENAME TABLE old_table1 TO new_table1, old_table2 TO new_table2, old_table3 TO new_table3;

示例

在下面的示例中,我们创建了三个不同的表,名为 **Cust1**、**Cust2** 和 **Cust3**:

CREATE TABLE Cust1(ID INT); CREATE TABLE Cust2(ID INT); CREATE TABLE Cust3(ID INT);

在这里,我们使用以下查询验证上述表是否已创建:

SHOW TABLES;

正如我们在下面的输出中看到的,上述表已成功创建。

tutorials 中的表
cust1
cust2
cust3

现在,让我们使用以下查询重命名所有上述创建的表:

RENAME TABLE Cust1 TO Buyer1, Cust2 TO Buyer2, Cust3 TO Buyer3;

输出

所有三个表都已重命名,没有任何错误。

Query OK, 0 rows affected (0.03 sec)

验证

让我们再次验证表的列表,以查找表名是否已更改:

SHOW TABLES;

正如我们在下面的输出中看到的,所有三个表都已成功重命名。

tutorials 中的表
buyer1
buyer2
buyer3

Learn MySQL in-depth with real-world projects through our MySQL certification course. Enroll and become a certified expert to boost your career.

使用 ALTER TABLE 语句重命名表

在 MySQL 中,我们还可以使用带有 **ALTER TABLE** 语句的 RENAME 来修改现有表的名称。

语法

以下是使用 ALTER TABLE 语句重命名表的语法:

ALTER TABLE existing_table_name RENAME TO new_table_name

示例

在以下查询中,我们创建了一个名为 **PLAYERS** 的表。

CREATE TABLE PLAYERS ( ID INT, NAME VARCHAR(20), AGE INT );

现在,让我们使用以下查询将上面创建的表重命名为新的名称 **TEAMS**:

ALTER TABLE PLAYERS RENAME TO TEAMS;

输出

表已重命名,没有任何错误。

Query OK, 0 rows affected (0.02 sec)

验证

执行以下查询以检索 PLAYERS 表的描述:

DESC PLAYERS;

它将显示错误,因为我们已将 PLAYERS 表重命名为 TEAMS,并且我们的数据库中不存在 PLAYERS 表。

ERROR 1146 (42S02): Table 'tutorials.players' doesn't exist

使用客户端程序重命名表

除了使用 MySQL 查询在 MySQL 数据库中重命名表外,我们还可以使用客户端程序对表执行 RENAME TABLE 操作。

语法

以下是各种编程语言中在 MySQL 数据库中重命名表的语法:

要通过PHP程序重命名MySQL数据库中的表,需要使用mysqli函数query()执行RENAME TABLE语句,如下所示:

$sql = "RENAME TABLE old_table_name TO new_table_name"; $mysqli->query($sql);

要通过Node.js程序重命名MySQL数据库中的表,需要使用mysql2库的query()函数执行RENAME TABLE语句,如下所示:

sql = "RENAME TABLE table_name TO new_name"; con.query(sql);

要通过Java程序重命名MySQL数据库中的表,需要使用JDBC函数executeUpdate()执行RENAME TABLE语句,如下所示:

String sql = "RENAME TABLE old_table_name TO new_table_name"; statement.executeUpdate(sql);

要通过Python程序重命名MySQL数据库中的表,需要使用MySQL Connector/Pythonexecute()函数执行RENAME TABLE语句,如下所示:

sql = "RENAME TABLE old_table_name TO new_table_name" cursorObj.execute(sql);

示例

以下为程序示例:

$dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'password'; $dbname = 'TUTORIALS'; $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if ($mysqli->connect_errno) { printf("Connect failed: %s", $mysqli->connect_error); exit(); } // printf('Connected successfully.'); $sql = "RENAME TABLE tutorials_table TO tutorials_tbl "; if ($mysqli->query($sql)) { printf("table renamed successfully."); } if ($mysqli->errno) { printf("table could not rename: %s", $mysqli->error); } $mysqli->close();

输出

获得的输出结果如下:

table renamed successfully.
var mysql = require('mysql2'); var con = mysql.createConnection({ host: "localhost", user: "root", password: "Nr5a0204@123" }); //Connecting to MySQL con.connect(function (err) { if (err) throw err; console.log("Connected!"); console.log("--------------------------"); //Creating a Database sql = "CREATE DATABASE tutorials" con.query(sql); //Selecting a Database sql = "USE tutorials" con.query(sql); //Creating DEMO table sql = "CREATE TABLE Demo(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255));" con.query(sql); //Inserting records sql = "INSERT INTO Demo VALUES(1, 'Shikhar', 'Dhawan'),(2, 'Jonathan', 'Trott'),(3, 'Kumara', 'Sangakkara');" con.query(sql); //Fetching the DEMO table sql = "SELECT * FROM Demo;" con.query(sql, function(err, result){ if (err) throw err console.log("**Following is the DEMO table**"); console.log(result); console.log("--------------------------"); }); //Renaming the DEMO table as PLAYERS sql = "RENAME TABLE Demo to Players;" con.query(sql, function(err, result){ if (err) throw err console.log("**Renamed the DEMO table as Players**"); console.log(result); console.log("--------------------------"); }); //Trying to Retrieve the DEMO table, Leads to an error. sql = "SELECT * FROM Demo;" con.query(sql, function(err, result){ if (err) throw err console.log("Trying to retrieve DEMO table"); console.log(result); }); });

输出

生成的输出结果如下:

Connected!
--------------------------
**Following is the DEMO table**
[
  { ID: 1, First_Name: 'Shikhar', Last_Name: 'Dhawan' },
  { ID: 2, First_Name: 'Jonathan', Last_Name: 'Trott' },
  { ID: 3, First_Name: 'Kumara', Last_Name: 'Sangakkara' }
]
--------------------------
**Renamed the DEMO table as Players**
ResultSetHeader {
  fieldCount: 0,
  affectedRows: 0,
  insertId: 0,
  info: '',
  serverStatus: 2,
  warningStatus: 0,
  changedRows: 0
}
--------------------------
C:\Users\Lenovo\desktop\JavaScript\connectDB.js:52
    if (err) throw err
             ^

Error: Table 'tutorials.demo' doesn't exist
    at Packet.asError (C:\Users\Lenovo\desktop\JavaScript\node_modules\mysql2\lib\packets\packet.js:728:17)
    at Query.execute (C:\Users\Lenovo\desktop\JavaScript\node_modules\mysql2\lib\commands\command.js:29:26)
    at Connection.handlePacket (C:\Users\Lenovo\desktop\JavaScript\node_modules\mysql2\lib\connection.js:478:34)
    at PacketParser.onPacket (C:\Users\Lenovo\desktop\JavaScript\node_modules\mysql2\lib\connection.js:97:12)
    at PacketParser.executeStart (C:\Users\Lenovo\desktop\JavaScript\node_modules\mysql2\lib\packet_parser.js:75:16)
    at Socket. (C:\Users\Lenovo\desktop\JavaScript\node_modules\mysql2\lib\connection.js:104:25)
    at Socket.emit (node:events:513:28)
    at addChunk (node:internal/streams/readable:315:12)
    at readableAddChunk (node:internal/streams/readable:289:9)
    at Socket.Readable.push (node:internal/streams/readable:228:10) {
  code: 'ER_NO_SUCH_TABLE',
  errno: 1146,
  sqlState: '42S02',
  sqlMessage: "Table 'tutorials.demo' doesn't exist",
  sql: 'SELECT * FROM Demo;',
  fatal: true
}        
import java.sql.*; public class RenameTable { public static void main(String[] args){ String url = "jdbc:mysql://localhost:3306/TUTORIALS"; String username = "root"; String password = "password"; try{ Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection = DriverManager.getConnection(url, username, password); Statement statement = connection.createStatement(); System.out.println("Connected successfully...!"); //Rename tables...! String sql = "RENAME TABLE tutorials_tbl TO new_table"; statement.executeUpdate(sql); System.out.println("Table renamed successfully successfully...!"); connection.close(); } catch(Exception e){ System.out.println(e); } } }

输出

获得的输出结果如下所示:

Table renamed successfully successfully...!      
import mysql.connector #establishing the connection connection = mysql.connector.connect( host='localhost', user='root', password='password', database='tut' ) old_table_name = 'tutorials_tbl' new_table_name = 'tutorials_table' #Creating a cursor object cursorObj = connection.cursor() cursorObj.execute(f"RENAME TABLE {old_table_name} TO {new_table_name}") print(f"Table '{old_table_name}' is renamed to '{new_table_name}' successfully.") cursorObj.close() connection.close()

输出

以下是上述代码的输出结果:

Table 'tutorials_tbl' is renamed to 'tutorials_table' successfully.
广告