How to import the famous quotes database in MySQL using Python

You'll have to import a sql file that contains SQL queries to your MySQL database. For this, the MySQL Connector package is required. Also, the importing per se is an execution of all queries from the provided SQL file.

pip install mysql-connector-python

As the mysql-connector is installed, you can define a connection to the running MySQL server, an existing or new one, and then proceed to the importing step. The following code will cover everything for a sql file execution and database import.

import mysql.connector

# define a connection to your database
# where USER, PASSWORD and DATABASE are your values

connection = mysql.connector.connect(
    user='USER', 
    password='PASSWORD',
    host='127.0.0.1', 
    database='DATABASE'
)

# open the sql file and execute it in a transaction

with open('famous_quotes.sql', 'r') as f:
    with connection.cursor() as cursor:
        cursor.execute(f.read(), multi=True)
    connection.commit()

connection.close()

If you are getting an error regarding the max_allowed_packet, you'll have to increase the max_allowed_packet variable in MySQL config file. This error is discussed here on Github.