python-mysqlHow do I truncate a MySQL table using Python?
To truncate a MySQL table using Python, you can use the TRUNCATE()
method of the MySQLdb
library. This method is used to delete all rows from a table without deleting the table itself.
Example code
import MySQLdb
db = MySQLdb.connect("localhost","user","password","database")
cursor = db.cursor()
cursor.execute("TRUNCATE TABLE table_name")
db.close()
The code above will delete all rows from the table table_name
in the database
.
Code explanation
-
import MySQLdb
: This imports theMySQLdb
library, which is used to connect to and work with a MySQL database. -
db = MySQLdb.connect("localhost","user","password","database")
: This connects to the MySQL database with the given credentials (user
andpassword
) and selects the databasedatabase
. -
cursor = db.cursor()
: This creates a cursor object which is used to execute queries. -
cursor.execute("TRUNCATE TABLE table_name")
: This executes theTRUNCATE()
method which deletes all rows from the tabletable_name
. -
db.close()
: This closes the connection to the database.
Helpful links
More of Python Mysql
- How can I connect Python to a MySQL database?
- How can I connect to MySQL using Python?
- How can I convert data from a MySQL database to XML using Python?
- How can I use Python and MySQL to generate a PDF?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How can I connect Python and MySQL?
- How do I connect Python with MySQL using XAMPP?
- How do I use a cursor to interact with a MySQL database in Python?
- How do I check the version of MySQL I am using with Python?
- How do I fix a bad MySQL handshake error in Python?
See more codes...