Python can handle many different types of databases. For each of these types a different API exists. So encourage similarity between those different API's, PEP 249 has been introduced.
This API has been defined to encourage similarity between the Python modules that are used to access databases. By doing this, we hope to achieve a consistency leading to more easily understood modules, code that is generally more portable across databases, and a broader reach of database connectivity from Python. PEP-249
Accessing MySQL database using MySQLdb
The first thing you need to do is create a connection to the database using the connect method. After that, you will need a cursor that will operate with that connection.
Use the execute method of the cursor to interact with the database, and every once in a while, commit the changes using the commit method of the connection object.
Once everything is done, don't forget to close the cursor and the connection.
Here is a Dbconnect class with everything you'll need.
Interacting with the database is simple. After creating the object, just use the execute method.
If you want to call a stored procedure, use the following syntax. Note that the parameters list is optional.
After the query is done, you can access the results multiple ways. The cursor object is a generator that can fetch all the results or be looped.
If you want a loop using directly the generator:
If you want to commit changes to the database:
If you want to close the cursor and the connection:
Creating a connection
According to PEP 249, the connection to a database should be established using a
connect() constructor, which returns a
Connection object. The arguments for this constructor are database dependent. Refer to the database specific topics for the relevant arguments.
This connection object has four methods:
Closes the connection instantly. Note that the connection is automatically closed if the
Connection.__del___ method is called. Any pending transactions will implicitely be rolled back.
Commits any pending transaction the to database.
Rolls back to the start of any pending transaction. In other words: this cancels any non-committed transaction to the database.
Cursor object. This is used to do transactions on the database.
Install the cx_Oracle package as:
sudo rpm -i <YOUR_PACKAGE_FILENAME>
Extract the Oracle instant client and set environment variables as:
Creating a connection:
Get database version:
Sample Output: ['12', '1', '0', '2', '0']
Execute query: SELECT
Output will be in Python tuples:
(10, 'SYSADMIN', 'IT-INFRA', 7)
(23, 'HR ASSOCIATE', 'HUMAN RESOURCES', 6)
Execute query: INSERT
When you perform insert/update/delete operations in an Oracle Database, the changes are only available within your session until
commit is issued. When the updated data is committed to the database, it is then available to other users and sessions.
Execute query: INSERT using Bind variables
Bind variables enable you to re-execute statements with new values, without the overhead of re-parsing the statement. Bind variables improve code re-usability, and can reduce the risk of SQL Injection attacks.
The close() method closes the connection. Any connections not explicitly closed will be automatically released when the script ends.
PostgreSQL Database access using psycopg2
psycopg2 is the most popular PostgreSQL database adapter that is both lightweight and efficient. It is the current implementation of the PostgreSQL adapter.
Its main features are the complete implementation of the Python DB API 2.0 specification and the thread safety (several threads can share the same connection)
Establishing a connection to the database and creating a table
Inserting data into the table:
Retrieving table data:
The output of the above would be:
And so, there you go, you now know half of all you need to know about psycopg2! :)
SQLite is a lightweight, disk-based database. Since it does not require a separate database server, it is often used for prototyping or for small applications that are often used by a single user or by one user at a given time.
The code above connects to the database stored in the file named
users.db, creating the file first if it doesn't already exist. You can interact with the database via SQL statements.
The result of this example should be:
The SQLite Syntax: An in-depth analysis
Import the sqlite module using
To use the module, you must first create a Connection object that represents the database. Here the data will be stored in the example.db file:
Alternatively, you can also supply the special name
:memory:to create a temporary database in RAM, as follows:
Once you have a
Connection, you can create a
Cursorobject and call its
execute()method to perform SQL commands:
Important Attributes and Functions of
It is an attribute used to get or set the current isolation level. None for autocommit mode or one of
The cursor object is used to execute SQL commands and queries.
Commits the current transaction.
Rolls back any changes made since the previous call to
Closes the database connection. It does not call
close()is called without first calling
commit()(assuming you are not in autocommit mode) then all changes made will be lost.
An attribute that logs the total number of rows modified, deleted or inserted since the database was opened.
These functions perform the same way as those of the cursor object. This is a shortcut since calling these functions through the connection object results in the creation of an intermediate cursor object and calls the corresponding method of the cursor object
You can change this attribute to a callable that accepts the cursor and the original row as a tuple and will return the real result row.
Important Functions of
Executes a single SQL statement. The SQL statement may be parametrized (i. e. placeholders instead of SQL literals). The sqlite3 module supports two kinds of placeholders: question marks
?(“qmark style”) and named placeholders
Beware: don't use
%sfor inserting strings into SQL commands as it can make your program vulnerable to an SQL injection attack (see SQL Injection ).
Executes an SQL command against all parameter sequences or mappings found in the sequence sql. The sqlite3 module also allows using an iterator yielding parameters instead of a sequence.
You can also pass iterator objects as a parameter to executemany, and the function will iterate over the each tuple of values that the iterator returns. The iterator must return a tuple of values.
This is a nonstandard convenience method for executing multiple SQL statements at once. It issues a
COMMITstatement first, then executes the SQL script it gets as a parameter.
sql_scriptcan be an instance of
The next set of functions are used in conjunction with
SELECTstatements in SQL. To retrieve data after executing a
SELECTstatement, you can either treat the cursor as an iterator, call the cursor’s
fetchone()method to retrieve a single matching row, or call
fetchall()to get a list of the matching rows.
Example of the iterator form:
Fetches the next row of a query result set, returning a single sequence, or None when no more data is available.
Fetches the next set of rows of a query result (specified by size), returning a list. If size is omitted, fetchmany returns a single row. An empty list is returned when no more rows are available.
Fetches all (remaining) rows of a query result, returning a list.
SQLite and Python data types
SQLite natively supports the following types: NULL, INTEGER, REAL, TEXT, BLOB.
This is how the data types are converted when moving from SQL to Python or vice versa.
To use sqlalchemy for database:
Now this engine can be used: e.g. with pandas to fetch dataframes directly from mysql