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
- How can I access MySQL using Python?
- How can I connect to MySQL using Python?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How do I access MySQL using Python?
- How do I connect Python with MySQL using XAMPP?
- How do I use Python to authenticate MySQL on Windows?
- How can I create a web application using Python and MySQL?
- How can I use Python Kivy with MySQL?
See more codes...