PYTHON Tutorial
Install a Data Connector:
pip install mysql-connector-python
pip install PyMySQL
pip install SQLAlchemy
Import the Connector:
import mysql.connector
Establish a Connection:
connection = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
Create a Cursor:
cursor = connection.cursor()
Execute Queries:
execute()
method to execute a queryfetchall()
method to retrieve results as a list of tuplesfetchone()
method to retrieve the next resultCommit Changes:
cursor.execute("INSERT INTO...")
connection.commit()
Close the Connection:
cursor.close()
connection.close()
import mysql.connector
# Connect to the database
connection = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
# Create a cursor
cursor = connection.cursor()
# Execute a query
cursor.execute("SELECT * FROM users")
# Retrieve the results
users = cursor.fetchall()
# Close the cursor and connection
cursor.close()
connection.close()
# Print the users
for user in users:
print(user)