Google News
logo
Python Program to Select all records from a table
To select all records from a MySQL table using Python, you can use the `SELECT` statement in combination with the `execute()` method of the cursor object. Here's an example Python program that selects all records from a `customers` table :

Example :
import mysql.connector

# Create a connection to the MySQL server
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)

# Create a cursor object to execute SQL statements
mycursor = mydb.cursor()

# Select all records from the table
mycursor.execute("SELECT * FROM customers")

# Fetch all the rows
rows = mycursor.fetchall()

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

# Close the connection
mydb.close()
In the above example, the program selects all records from the `customers` table using the `execute()` method of the cursor object. The `SELECT` statement is passed as a string argument to the `execute()` method.

After the statement has been executed, the program fetches all the rows using the `fetchall()` method of the cursor object. This method returns a list of tuples, where each tuple represents a row in the result set.

Finally, the program prints the rows using a `for` loop and closes the connection.