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],[database ...
Get MySQL for Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.