You can execute a SELECT sql query through the cursor.execute()
method to query some rows from a mysql table.
Syntax
cursor.execute("SELECT column1, column2 FROM table_name WHERE condition")
Select ALL Users
import mysql.connector # Establish connection to MySQL server connection = mysql.connector.connect( host="localhost", user="root", password="password", database="mydatabase" ) cursor = connection.cursor() # Execute a simple SELECT query cursor.execute("SELECT * FROM users") # Fetch all rows rows = cursor.fetchall() for row in rows: print(row) connection.close()
In this example, you use cursor.execute()
method to execute a sql select query. Then, you can use cursor.fetchall()
to fetch all rows you have selected.
Select with Condition
You can create a select sql with condition to query.
import mysql.connector # Establish connection to MySQL server connection = mysql.connector.connect( host="localhost", user="root", password="password", database="mydatabase" ) cursor = connection.cursor() # Execute a SELECT query with a condition name = "Alice" cursor.execute("SELECT * FROM users WHERE name = %s", (name,)) # Fetch one row row = cursor.fetchone() print(row) connection.close()