How to Rename a MySQL Table in Python 


               


How to Rename a MySQL Table In Python



Python


In this article, we show how to rename a MySQL table in Python.

If you need to know how to install MySQL, see How to Install MySQL in Python 3.

So, the code to rename a MySQL table is shown below.



The full code to rename a table is shown below.



So, this is all the code that is needed to rename a MySQL table in Python.

So, the first thing we have to do is import the MySQLdb.

Once we have MySQLdb imported, then we create a variable named db. We set db equal to the MySQLdb.connect() function. This function will allow us to connect to a database. In side of this MySQLdb.connect() function are 4 parameters. These are, MySQLdb.connect("hostname", "username", "password", "database_name"). This line establishes connection with the database that you want.

We then create a variable named cursor, which we set equal to db.cursor(). This establishes a cursor for the database.

Next, we execute our function to rename the table using the cursor.execute() function. Inside of this function, we place in the line, "Alter TABLE Table_name RENAME to Table_renamed". So the whole line of code, is, cursor.execute("Alter TABLE Table_name RENAME to Table_renamed"). Table_name is the original name of the table. Table_renamed is the name that you want to change the table to.

If the function executes and the table name is renamed, a '0' will be output. This alerts you that the renaming of the table has been successful.

And this is how we can rename a MySQL table in Python.


Related Resources

How to Show All Tables of a MySQL Database in Python

How to Count the Number of Rows in a MySQL Table in Python



HTML Comment Box is loading comments...