Here are the steps to access a MySQL database using Python and a car example:
1.Install the mysql-connector-python
library:
1 |
pip install mysql-connector-python |
2. Connect to the MySQL database:
1 2 3 4 5 6 7 8 9 10 |
import mysql.connector # Connect to the database conn = mysql.connector.connect( host="hostname", user="username", password="password", database="database_name" ) |
3. Create a table to store information about cars:
1 2 3 4 5 6 7 8 9 10 11 |
# Create a cursor to execute SQL statements cursor = conn.cursor() # Create a table to store information about cars cursor.execute(""" CREATE TABLE cars ( id INT AUTO_INCREMENT PRIMARY KEY, make VARCHAR(255), model VARCHAR(255) ) """) |
4. Add data to table:
1 2 3 4 5 6 |
# Add a car to the table cursor.execute(""" INSERT INTO cars (make, model) VALUES ("Toyota", "Corolla") """) conn.commit() |
5. Retrieve data from the table:
1 2 3 4 5 6 7 |
# Retrieve all cars from the table cursor.execute("SELECT * FROM cars") cars = cursor.fetchall() # Loop through the cars and print the make and model for car in cars: print(car[1], car[2]) |
6. Close the connection:
1 2 3 |
# Close the cursor and connection cursor.close() conn.close() |
This code demonstrates how to connect to a MySQL database, create a table to store information about cars, add data to the table, retrieve data from the table, and close the connection. The code uses the mysql-connector-python
library to interact with the MySQL database.