Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Setting Up Connection to MySQL Server

00:00 So far, you have installed the complete MySQL system, and now is the time to set up a connection to the MySQL server. In this lesson, you will learn how to write a Python code that establishes this connection in a secure way.

00:15 Open your favorite Python IDE. On my side, I’m opening Visual Studio Code. Next, open the designated MySQLproject folder. In this folder, create a new Jupyter Notebook.

00:35 Let’s call it MySQLcode.

00:43 Make sure to select the utils Python environment as a Python kernel to enable running and introspecting the Notebook in the utils virtual environment.

00:54 Next, you’ll need the built-in getpass module. Type from getpass import getpass. You will need it to hide your login credentials such as passwords.

01:09 From mysql.connector, you will need the connect() function, import connect, and Error to report any errors that may occur while establishing the connection to the server.

01:25 For this purpose, you should try using a try except structure: try: except Error as e: print(e).

01:40 Also, in this code, you should take advantage of a context manager using with as it takes care of the connection cleanup. with connect

01:54 as connection: print( connection). An alternative solution is to close the connection after you are done accessing the database. Otherwise, if you leave open connections unused, you may encounter server performance issues.

02:16 The connect() function takes in your login credentials that you have set up during the server installation process, such as the values of the host, username, and password parameters.

02:35 The host is your localhost. Since you have set up the server on your local machine, type localhost. To avoid the exposure of sensitive information, which is a good practice for deployment, you can use input and getpass commands to prompt a user for login credentials.

03:00 user = input( "Enter your username: ")

03:08 and password = getpass("Enter your password: "). Let’s execute this code.

03:20 It expects input data from the user, and in Visual Studio Code, the input command line appears above the cell with a prompt to enter your username and its root, followed by your password.

03:37 Type your password.

03:41 Do you see a MySQL object in the form of a long string appearing as a result of the cell execution? Congratulations, you have now established a successful connection between your Jupyter notebook and the MySQL server without posing a security risk.

Become a Member to join the conversation.