Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีก็อปปี้ตารางใน MySQL ด้วย Python


สามารถสร้างสำเนาตารางที่มีอยู่ใน MySQL ผ่าน Python ได้ โดยจะคัดลอกทั้งโครงสร้างคอลัมน์ นิยามคอลัมน์ และข้อมูลทุกแถว

ไวยากรณ์

CREATE TABLE new_table_name SELECT * FROM existing_table
  • new_table_name: ชื่อตารางใหม่ที่จะสร้าง
  • existing_table: ชื่อตารางที่ต้องการคัดลอก

ขั้นตอนก็อปปี้ตารางด้วย MySQL ใน Python

  • นำเข้า MySQL Connector

  • สร้างการเชื่อมต่อด้วย connect()

  • สร้างออบเจ็กต์ cursor ด้วย cursor()

  • สร้างคำสั่ง SQL ที่เหมาะสม

  • รันคำสั่งด้วย execute()

  • ปิดการเชื่อมต่อ

สมมติว่ามีตาราง 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()
# คัดลอกตาราง Students เป็น CopyStudents
query = "CREATE TABLE CopyStudents SELECT * FROM Students"
cursor.execute(query)
# ดูข้อมูลในตารางใหม่
query1 = "SELECT * FROM CopyStudents"
cursor.execute(query1)
for row in cursor:
    print(row)
db.close()

ผลลัพธ์

('Karan', 4, 'Amritsar', 95)
('Sahil', 6, 'Amritsar', 93)
('Kriti', 3, 'Batala', 88)
('Khushi', 9, 'Delhi', 90)
('Kirat', 5, 'Delhi', 85)

ทุกแถว คอลัมน์ และนิยามคอลัมน์จาก Students ถูกคัดลอกไปยัง CopyStudents