python-mysqlHow do I add a column to a MySQL table using Python?
To add a column to a MySQL table using Python, you need to use the ALTER TABLE statement. This statement is used to modify the structure of an existing table. For example:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
sql = "ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY"
mycursor.execute(sql)
print(mycursor.rowcount, "record(s) affected")
This will add a column named id to the customers table with an auto-incrementing integer as the primary key. The output will be 1 record(s) affected.
Code explanation
import mysql.connector: imports the MySQL Connector Python module.mydb = mysql.connector.connect(host="localhost", user="yourusername", passwd="yourpassword"): connects to the MySQL database.mycursor = mydb.cursor(): creates a cursor object.sql = "ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY": the SQL statement to add a column to thecustomerstable.mycursor.execute(sql): executes the SQL statement.print(mycursor.rowcount, "record(s) affected"): prints the number of records affected.
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...