python-mysqlHow can I get the column names from a MySQL database using Python?
You can get the column names from a MySQL database using Python by using the cursor.description
attribute. This attribute returns information about the columns in the result set of a query as a sequence of 7-item tuples
. Here is an example:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
for x in mycursor.description:
print(x[0])
# Output:
# name
# address
# age
The code above connects to a MySQL database, executes a query and prints the column names from the result set. The mycursor.description
attribute returns a sequence of 7-item tuples. Each tuple contains information about the columns in the result set, with the first item in the tuple being the column name.
Helpful links
More of Python Mysql
- How can I use Python to interact with a MySQL database using YAML?
- How can I connect Python to a MySQL database?
- How do I use Python to query MySQL with multiple conditions?
- How can I use Python to retrieve data from MySQL?
- How do I use Python to authenticate MySQL on Windows?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I convert a MySQL database to a SQLite database using Python?
- How do I update a MySQL database with variables using Python?
- How do I update a MySQL database using Python?
- How do I use Python to show the MySQL processlist?
See more codes...