Connecting to the database

(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

Before we start using our database with python we must connect to it. There are four stages of database communication with python:

  1. Create a connection object.
  2. Create a cursor object to read/write.
  3. Interact with the database.
  4. Close the connection.

Note: We will be using world mysql database so first download and import database as follows:

First login to your mysql server

You will be asked for password at this point, enter your password and hit the enter key.

Connecting to the database

To connect to the database you need to use connect()  method.



On success connect()  method returns a connection object otherwise OperationalError  exception will be thrown.

Notice the import statement in the first line import print_function from __future__  , this allows us to use python 3 version of print()  function in python 2.

Expected Output:

Creating cursor object

Before you start interacting with the database you need to create cursor object.

Syntax : connection_object.cursor()

On success it returns Cursor object, otherwise an exception will be thrown.

Expected Output:

Interacting with the database

cursor object has execute()  method which you can use to execute sql queries.

Syntax: cursor.execute(sql)

On success it returns number of affected rows, otherwise it throws an exception.

Expected Output:

Closing the connection

After interacting with the database you need to close the database connection to give up resources.

Syntax: connection_object.close()


Now you know how to connect with database, execute queries and close the connection. In the next we will learn more about query operation.

Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

One thought on “Connecting to the database

Leave a Reply

Your email address will not be published. Required fields are marked *