In this article, we will create a table in MySQL and will create a copy of that table using Python. We will copy the entire table, including all the columns and the definition of the columns, as well as all rows of data in the table.
To connect to MySQL database using python, we need PyMySql module. The cursor class allows python to execute SQL commands. Cursors are created by connection_name.cursor() method, where connection_name is the link made to SQL Database. Once the connection is established, cursor.execute() is used to run the SQL statements.
Let us understand the above by taking an example. Suppose, in MySQL we create a database test and it contains a table named geeksforgeeks and has the below schema and following data:

SQL Database
To Copy a Table in MySQL we use the below query:
CREATE TABLE table-name SELECT * FROM table-name;
Now, below is the program to copy the entire table using python:
Python3
import pymysql
connection = pymysql.connect(
host = "localhost" ,
user = "root" ,
password = "1234" ,
port = 3306 ,
db = "test"
)
mycursor = connection.cursor()
mycursor.execute( "create table geeksforgeekscopy select * from geeksforgeeks" )
mycursor.execute( "Show tables" )
query1 = mycursor.fetchall()
for i in query1:
print (i)
mycursor.execute( "Select * from geeksforgeekscopy" )
query2 = mycursor.fetchall()
for i in query2:
print (i)
|
Output:

Python output
In the above figure, we could see the list of tables followed by all records from the geeksforgeekscopy table. The above output has also been confirmed by providing the output of MySQL database.

MySQL Output
Here is another example which depicts how to create a new table from the data and schema of a previous table. Below is the previously existing table:

Now, using the below script to create a copy of the above table in the database:
Python3
import pymysql
connection = pymysql.connect( "localhost" , "root" , " ", " geek")
mycursor = connection.cursor()
mycursor.execute( "create table geeksdemocopy select * from geeksdemo" )
mycursor.execute( "Show tables" )
query1 = mycursor.fetchall()
for i in query1:
print (i)
mycursor.execute( "Select * from geeksdemocopy" )
query2 = mycursor.fetchall()
for i in query2:
print (i)
|
Output:

Below is the new table whose data and schema are copied from the previous table:
