MySQL Database
Python can be used for database applications.
One of the most popular databases is MySQL.
In order to be able to try the code examples in this tutorial, you should have MySQL installed on your computer.
You can find more information on theMySQL Official Site Download the MySQL database.
Installing the MySQL Driver
Python requires a MySQL driver to access a MySQL database.
In this tutorial we will use the "MySQL Connector" driver.
We recommend that you use the PIP to install the MySQL Connector.
PIP is most likely already installed in your Python environment.
Navigate to the location of the PIP on the command line and enter the following:
Download and install "MySQL Connector":
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>python -m pip install mysql-connector-python
You have now downloaded and installed the MySQL driver.
Testing the MySQL Connector
To test if the installation was successful, or if you have already installed the "MySQL Connector", create a Python page containing the following:
demo_mysql_test.py
:
import
If there are no errors in the above code, "MySQL Connector" is installed and ready to use.
Create Connection
First create a connection to the database.
Use your MySQL database username and password:
demo_mysql_connection.py
:
import mydb = ( host="localhost", user="yourusername", password="yourpassword" ) print(mydb)
Creating a database
To create a database in MySQL, use the "CREATE DATABASE" statement:
The example creates a database named "mydatabase":
import mydb = ( host="localhost", user="yourusername", password="yourpassword" ) mycursor = () ("CREATE DATABASE mydatabase")
If there are no errors in the above code, then you have successfully created a database.
Check if the database exists
You can check for the existence of a database by using the "SHOW DATABASES" statement to list all databases on the system:
Example returns a list of databases in the system:
import mydb = ( host="localhost", user="yourusername", password="yourpassword" ) mycursor = () ("SHOW DATABASES") for x in mycursor: print(x)
Alternatively, you can try to access the database while establishing a connection:
The example tries to connect to the database "mydatabase":
import mydb = ( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" )
This is the detailed content of Python Database Installation and MySQL Connector Application Tutorial, for more information about Python MySQL Connector, please pay attention to my other related articles!