PYTHON Tutorial
cursor()
method to create a cursor object.execute()
method.fetchone()
or fetchall()
methods to retrieve one or all rows in the result set.import mysql.connector
# Establish database connection
conn = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
# Create cursor
cursor = conn.cursor()
# Execute SELECT statement
cursor.execute("SELECT * FROM table_name")
# Fetch all rows
rows = cursor.fetchall()
# Print result set
for row in rows:
print(row)
# Update a record
cursor.execute("UPDATE table_name SET column_name = 'new value' WHERE id = 1")
# Commit changes
conn.commit()
# Close cursor and connection
cursor.close()
conn.close()