Installing MySQL Database
You need to have MySQL installed on your computer in order to play around with the code samples in this tutorial.
You can download a free MySQL database at https://www.mysql.com/downloads/.
Install MySQL Driver
To use Python with MySQL, you need to install the MySQL database on your computer and the MySQL Connector Python driver. This can be done using PIP, which is likely already installed in your Python environment. To install the driver, navigate to the location of PIP in your command line and type:
pip install mysql-connector-python
You have successfully installed a MySQL driver on your system.
To test if the driver was installed successfully, create a Python script with the following code:
import mysql.connector
If the above code shows no errors, “MySQL Connector” is installed and ready to be used.
Create Connection
To create a connection to a MySQL database, use the mysql.connector.connect()
method and provide the necessary information, such as the host, username, and password. You can then use SQL statements to query the database.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
print(mydb)
You can now use SQL statements to query the database.