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 retrieve data from MySQL?
- How can I use Python and MySQL to create a login system?
- How can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
- How can I host a MySQL database using Python?
- How do I fix a bad MySQL handshake error in Python?
- How can I connect Python to a MySQL database using an Xserver?
- How do I connect Python with MySQL using XAMPP?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python and MySQL?
See more codes...