Open In App

Access Relation Databases with Python

Databases are powerful tools for data scientists. DB-API is Python’s standard API used for accessing databases. It allows you to write a single program that works with multiple kinds of relational databases instead of writing a separate program for each one. This is how a typical user accesses databases using Python code written on a Jupyter notebook, a Web-based editor.



There is a mechanism by which the Python program communicates with the DBMS:



The two main concepts in the Python DB-API are:

1) Connection objects used for

Following are a few connection methods:

2) Query objects are used to run queries.

This is a python application that uses the DB-API to query a database.




from dbmodule import connect
  
# Create connection object
connection = connect('databasename', 'username', 'pswd')
  
# Create a cursor object
cursor = connection.cursor()
  
# Run queries
cursor.execute('select * from mytable')
results = cursor.fetchall()
  
# Free resources
cursor.close()
connection.close()

  1. First, we import the database module by using the connect API from that module. To open a connection to the database, you use the connection function and pass in the parameters that are the database name, username, and password. The connect function returns the connection object.
  2. After this, we create a cursor object on the connection object. The cursor is used to run queries and get the results.
  3. After running the queries using the cursor, we also use the cursor to fetch the results of the query.
  4. Finally, when the system is done running the queries, it frees all resources by closing the connection. Remember that it is always important to close connections to avoid unused connections taking up resources.
Article Tags :