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 do I set up a secure SSL connection between Python and MySQL?
- How can I export data from a MySQL database to a CSV file using Python?
- How do I use a SELECT statement in Python to query a MySQL database?
- How do I use a Python MySQL refresh cursor?
- How can I compare and contrast using Python with MySQL versus PostgreSQL?
- How can I fix a "MySQL server has gone away" error when using Python?
- How do I install a Python package from PyPI into a MySQL database?
- How can I use Python and MySQL to generate a PDF?
- How do I use Python to update multiple columns in a MySQL database?
- How can I connect Python to a MySQL database?
See more codes...