Fireside chats with Perplexity AI:
How to connect a MySQL database using Python3?
import mysql.connector
# Establish the connection
connection = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database_name"
)
# Create a cursor object to interact with the database
cursor = connection.cursor()
# Execute a query
cursor.execute("SELECT * FROM your_table_name")
# Fetch the results
results = cursor.fetchall()
# Print the results
for row in results:
print(row)# Close the cursor and connection
cursor.close()
How do you install MySQL?
pip install mysql-connector-python
Install the MySQL Connector/Python module:
Replace the placeholder values in the connect() method:
"localhost" with your MySQL server's hostname
"your_username" with your MySQL username
"your_password" with your MySQL password
"your_database_name" with the name of the database you want to connect to
Replace "your_table_name" in the execute() method with the name of the table you want to query.
This code establishes a connection to your MySQL database, executes a SELECT query, fetches the results, and then closes the connection. You can modify the SQL query in the execute() method to perform different operations on your database.Remember to handle exceptions and close the connection properly in your actual code:
try:
# Your database operations here
pass
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
Leave A Comment