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 theMySQLdblibrary, 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 (userandpassword) 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
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How do I connect Python with MySQL using XAMPP?
- How can I use Python and MySQL to create a login system?
- How can I use Python and MySQL to generate a PDF?
- How do I use Python to connect to a MySQL database using XAMPP?
- How do Python and MySQL compare to MariaDB?
- How can I convert data from a MySQL database to XML using Python?
- How do I update a row in a MySQL database using Python?
- How do I set up a secure SSL connection between Python and MySQL?
- How can I use Python to retrieve data from MySQL?
See more codes...