How can I connect Python Application to MySQL

Python Application Connection to MySQL

MySQL is a highly popular open source database, used by developers all over the world. In this instruction we’ll show you how to connect my Python application, hosted within Cloudjiffy Cloud, to this DB server.

1. In the below example, we have both Python and MySQL servers within a single environment. You can create similar one, use separate environments for your app server and database or work with any external instances.
     
2. Access the application server via Cloudjiffy SSH Gate.
    

3. Now, install a MySQL connector for Python with the following command:

pip install mysql-connector==2.1.6
 
    

Note: In order to use the newer version of the MySQL connector, you need to additionally install Protobuf C++ of the 2.6.0 version or above.

4. Next, let’s create a simple script to establish connection. you can use any preferable text editor for this task, as well as any filename with the .py extension (e.g. vim script.py).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import mysql.connector
from mysql.connector import errorcode
try:
 cnx = mysql.connector.connect(user='{user}', password='{password}', host='{host}', database='{database}')
except mysql.connector.Error as err:
 if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
   print("Something is wrong with the user name or password")
 elif err.errno == errorcode.ER_BAD_DB_ERROR:
   print("Database does not exist")
 else:
   print(err)
else:
 print("I am connected!")
 cnx.close()

 

Here, you need to adjust the connection string (all the required information is provided within email for the MySQL node):
  • {user} - username to log into database with
  • {password} - password for the appropriate user
  • {host} - link to your MySQL container
  • {database} - database to be accessed (e.g. the default mysql one)

    

This script will connect to the specified database server with the provided credentials and will print connection errors (if any) or just a “You are connected!” phrase.

5. So, let’s execute our code with the appropriate command:

python script.py


If the “You are connected!” string appeared within terminal, the connection was successful. Now, you can be sure that your database server is accessible and can extend code to execute all of the required actions.


Was this article helpful?

mood_bad Dislike 0
mood Like 0
visibility Views: 12579