# Import the necessary libraries
import mysql.connector
import pandas as pd
Set up a connection to MySQL server running on the same machine as the Python code.¶
host: This parameter specifies the hostname or IP address of the MySQL server you want to connect to. In this case, it is set to “localhost”, which means that the MySQL server is running on the same machine as the Python code.
port: This parameter specifies the port number that the MySQL server is listening on. The default port for MySQL is 3306, which is what is being used here.
user: This parameter specifies the username that will be used to authenticate the connection to the MySQL server. In this case, it is set to “root”, which is a common default username for MySQL.
password: This parameter specifies the password that will be used to authenticate the connection to the MySQL server.
mydb = mysql.connector.connect(
host="localhost",
port="3306",
user="root",
password="***")
This line of code creates a cursor object that can be used to execute SQL statements on the MySQL database.
mydb is the database connection object that was previously established using the mysql.connector.connect() method. This object represents the connection to the MySQL server and can be used to interact with the database.
cursor() is a method of the database connection object that creates a new cursor object. The cursor is a temporary workspace that allows you to execute SQL statements and fetch results from the database. mycursor is a variable that stores the cursor object. You can use this cursor to execute SQL statements and interact with the database.
mycursor = mydb.cursor()
mycursor.execute(“CREATE DATABASE db_python”) executes an SQL statement to create a new database named “db_python”. This statement is sent to the MySQL server to be executed.
mycursor.execute(“USE db_python”) executes an SQL statement to select the “db_python” database as the active database for further operations. This statement tells the MySQL server to use the “db_python” database for any subsequent SQL statements that are executed through the mycursor object.
mycursor.execute("CREATE DATABASE db_python")
mycursor.execute("USE db_python")