python-mysqlHow do I select a table from a MySQL database using Python?
To select a table from a MySQL database using Python, the following code can be used:
import mysql.connector
# Connect to the database
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="password",
database="database_name"
)
# Create a cursor (an object to interact with the database)
mycursor = mydb.cursor()
# Select a table
mycursor.execute("SELECT * FROM table_name")
# Fetch all the data from the table
myresult = mycursor.fetchall()
# Print the data
for row in myresult:
print(row)
The code above will output the data from the selected table in the database.
Code explanation
import mysql.connector
- imports the MySQL Connector module, which is used to connect to a MySQL database.mydb = mysql.connector.connect(host="localhost", user="user", passwd="password", database="database_name")
- connects to the database.mycursor = mydb.cursor()
- creates a cursor object to interact with the database.mycursor.execute("SELECT * FROM table_name")
- selects a table from the database.myresult = mycursor.fetchall()
- fetches all the data from the selected table.for row in myresult: print(row)
- prints the data from the table.
Helpful links
More of Python Mysql
- How can I use Python to retrieve data from MySQL?
- How can I connect to MySQL using Python?
- How do I use a SELECT statement in Python to query a MySQL database?
- How can I connect Python and MySQL?
- How can I connect Python to a MySQL database?
- How do I use Python to query MySQL with multiple conditions?
- How can I use Python to interact with a MySQL database using YAML?
- How can I avoid MySQL IntegrityError when using Python?
- How do I format a date in MySQL using Python?
- How do I use Python to authenticate MySQL on Windows?
See more codes...