如何使用 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 千加瀏覽

開啟你的 事業

完成本課程以獲得認證

開始
廣告