Google News
logo
Python Program to Select only some of the columns in a table
Here's a Python program to select only some of the columns in a table :
Program :
import mysql.connector

# Establish a connection to the database
db = mysql.connector.connect(
    host="localhost",
    user="yourusername",
    password="yourpassword",
    database="yourdatabase"
)

# Create a cursor object to execute queries
cursor = db.cursor()

# Execute the query to select specific columns from a table
cursor.execute("SELECT column1, column2 FROM tablename")

# Fetch all the rows returned by the query
rows = cursor.fetchall()

# Display the rows
for row in rows:
    print(row)

# Close the database connection
db.close()
In this program, we first establish a connection to the MySQL database using the `mysql.connector` module. We then create a cursor object to execute queries.

The `SELECT` statement is used to select specific columns from a table. In this example, we are selecting `column1` and `column2` from a table called `tablename`. You can replace these column names and table name with your own.

The `fetchall()` method is used to fetch all the rows returned by the query. We then iterate through the rows and display them using a `for` loop.

Finally, we close the database connection using the `close()` method.