How to Connect to a MySQL Database In Python
In this article, we show how to connect to a MySQL database in Python.
So, the approach that we take is we import the pymysql module and then use the line, pymysql.install_as_MySQLdb(), to convert from pymysql to MySQL. We can then import the MySQL database.
If you need to know how to install MySQL, see How to Install MySQL in Python 3.
So, the code to connect to a MySQL database in Python is shown
below.
So, this is all the code that is needed to connect to a MySQL database (establish connection with a MySQL database).
So, the first thing we have to do is import the MySQLdb.
If you doing this through the pymysql module, then you first import the pymysql module and then install the MySQLdb from the pymysql module. We can then import the MySQLdb.
If you have the MySQLdb package directly installed, then the only import you need is MySQLdb and you leave out the first two lines (that contain pymysql).
So once we have MySQLdb imported, then we create a variable named db. We set db equal to the MySQLdb.connect() function. This function will allow us to connect to a database.
I'm assuming in this article, you don't want to do something as boring as connect to localhost. If you want to, that's fine. However, why not do the real thing? Connect to an actual MySQL database on a server.
So the MySQLdb.connect() function takes in 4 parameters. We will go over each of these now.
The first parameter is the hostname. This might end with something like database_name.db.number.hostedresource.com, depending on your server.
The second parameter is the username to log into the database. This is whatever username you created to connect to the MySQL database on your website.
The third parameter is the password. This is the password you created to log into the MySQL database on your website.
The fourth parameter is the name of the database you want to
establish connection to.
And this is all that you need to connect to a MySQL database
in Python.
Related Resources
How to Randomly Select From or Shuffle a List in Python