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
- How do I download MySQL-Python 1.2.5 zip file?
- How can I connect Python to a MySQL database?
- How do I connect Python with MySQL using XAMPP?
- How do I insert NULL values into a MySQL table using Python?
- How can I use Python and MySQL to generate a PDF?
- How can I access MySQL using Python?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How can I use Python Kivy with MySQL?
- How do I access MySQL using Python?
- How can I connect to MySQL using Python?
See more codes...