How to Select Only Some of Columns in a Table in Python MySQL


In this example, we will learn how to select only some of the columns in a table in Python MySQL.

Source Code

import mysql.connector

# connect to server
mydb = mysql.connector.connect(
    host="localhost",
    port=3306,
    user="yourusername",
    password="yourpassword",
    db="mydatabase"
)

# get a cursor
mycursor = mydb.cursor()

# execute a query
mycursor.execute("SELECT State_name, Abbreviation FROM us_state")

results = mycursor.fetchall()

for row in results:
    print(row)

# close the connection
mydb.close()

Output:

('Alabama', 'AL')
('Alaska', 'AK')
('Arizona', 'AZ')
('Arkansas', 'AR')
('California', 'CA')
('Colorado', 'CO')
('Connecticut', 'CT')
('Delaware', 'DE')
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments