O'Reilly logo

MySQL for Python by Albert Lukaszewski, PhD

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Connecting with a database

In making a phone call, one picks up the handset, dials a number, talks and listens, and then hangs up. Making a database connection through MySQL for Python is nearly as simple. The four stages of database communication in Python are as follows:

  • Creating a connection object
  • Creating a cursor object
  • Interacting with the database
  • Closing the connection

Creating a connection object

As mentioned previously, we use connect() to create an object for the program's connection to the database. This process automates logging into the database and selecting a database to be used.

The syntax for calling the connect() function and assigning the results to a variable is as follows:

[variable] = MySQLdb.connect([hostname], [username], [password], ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required