Connecting to the database

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.

Leave a Reply

Be the First to Comment!

Notify of