如何使用 Python 复制 MySQL 中的表?


我们可以用 Python 创建现有表的副本。它将复制整个表,包括列、列定义和所有表行。

语法

CREATE TABLE table_name SELECT * FROM existing_table

table_name 是要创建的新表的名称。existing_table 是要复制的表的名称。

用 Python 中的 MySQL 复制表的步骤

  • 导入 MySQL 连接器

  • 使用 connect() 建立与连接器的连接

  • 使用 cursor() 方法创建游标对象

  • 使用适当的 mysql 语句创建查询

  • 使用 execute() 方法执行 SQL 查询

  • 关闭连接

假设,我们有一个名为“Students”的表,如下所示

+----------+---------+-----------+------------+
|    Name  |  Class  |    City   |    Marks   |
+----------+---------+-----------+------------+
|    Karan |    4    | Amritsar  |    95      |
|    Sahil |    6    | Amritsar  |    93      |
|    Kriti |    3    | Batala    |    88      |
|   Khushi |    9    | Delhi     |    90      |
|    Kirat |    5    | Delhi     |    85      |
+----------+---------+-----------+------------+

示例

我们想要创建上述表的副本。为复制的表命名为“CopyStudents”。

import mysql.connector
db=mysql.connector.connect(host="your host", user="your username", password="your
password",database="database_name")

cursor=db.cursor()

#copy table Students into CopyStudents
query="CREATE TABLE CopyStudents SELECT * FROM Students"
cursor.execute(query)

#select rows from the new table
query1="SELECT * FROM CopyStudents"
cursor.execute(query1)

#print the contents of the copied table
for row in cursor:
   print(row)
db.close()

输出

(‘Karan’, 4 ,’Amritsar’ , 95)
(‘Sahil’ , 6 , ‘Amritsar’ ,93)
(‘Kriti’ , 3 , ‘Batala’ ,88)
(‘Amit’ , 9 , ‘Delhi’ , 90)
(‘Priya’ , 5 , ‘Delhi’ ,85)

表“Students”的所有行、列和列定义都会复制到“CopyStudents”表中。

更新于: 2021 年 6 月 10 日

3 千加浏览

开启你的 事业

完成本课程以获得认证

开始
广告
© . All rights reserved.