Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

SQLite – Python


May 16, 2021 SQLite


Table of contents


SQLite - Python

Installation

SQLite3 can be integrated with Python using the sqlite3 module. T he sqlite3 module was written by Gerhard Haring. I t provides a SQL interface that is compatible with the DB-API 2.0 specification described by PEP 249. You do not need to install the module separately, as the Python 2.5.x version above brings the module by default.

In order to use the sqlite3 module, you must first create a connection object that represents the database, and then you can selectively create a cursor object, which will help you execute all the SQL statements.

Python sqlite3 module API

Here are some important sqlite3 module programs to meet your needs for using the SQLite database in your Python program. If you need more details, check out the official documentation for the Python sqlite3 module.

Serial number API & Description
1 sqlite3.connect(database [,timeout ,other optional arguments])

The API opens a link to the SQLite database file Database.You can use ": Memory:" to open a database connection to the Database in the RAM instead of opening on the disk.If the database is successfully opened, a connection object is returned.

When a database is accessed by multiple connections, and one of them modifies the database, the SQLite database is locked until the transaction is submitted.The Timeout parameter represents the duration of the connection waiting to be locked until an abnormal disconnect connection occurs.The Timeout parameter is 5.0 (5 seconds).

If a given database name filename does not exist, the call will create a database.If you don't want to create a database in the current directory, you can specify a file name with the path so you can create a database in any place.

2 connection.cursor([cursorClass])

This routine creates one cursor Will be used in the Python database programming.This method accepts a single optional parameter CursorClass.If this parameter is provided, it must be a custom Cursor class extends from SQLite3.cursor.

3 cursor.execute(sql [, optional parameters])

This routine performs a SQL statement.The SQL statement can be parameterized (ie, the placeholder is used instead of SQL text).The SQLITE3 module supports two types of placeholders: question mark and name placeholder (name style).

For example: Cursor.execute ("INSERT INTO People VALUES (?,?)", (WHO, AGE))

4 connection.execute(sql [, optional parameters])

This routine is a shortcut to the method provided by the cursor object, which creates an intermediate cursor object by calling the cursor method, and then calls the cursor's Execute method by a given parameter.

5 cursor.executemany(sql, seq_of_parameters)

This routine executes a SQL command for all parameters or mappings in SEQ_OF_PARAMETERS.

6 connection.executemany(sql[, parameters])

This routine is a shortcut to the intermediate cursor object created by the Cursor method, and then call the cursor's ExecuteMANY method through a given parameter.

7 cursor.executescript(sql_script)

Once the routine receives the script, multiple SQL statements are executed.It first executes the commit statement and then executes the SQL script that is incorporated into the parameters.All SQL statements should be separated by a semicolon (;).

8 connection.executescript(sql_script)

This routine is a shortcut to the intermediate cursor object created by the Cursor method, and then call the cursor's ExecuteScript method through a given parameter.

9 connection.total_changes()

This routine returns the total number of databases that are modified, inserted or deleted since the database connection is open.

10 connection.commit()

This method submits the current transaction.If you have not called this method, then any action you have made since your last call commit () is invisible to other database connections.

11 connection.rollback()

This method rolls back to the changes to the database since the last time ().

12 connection.close()

This method closes the database connection.Please note that this will not call commit ().If you have not called a commit () method before, close the database connection directly, all changes you have done will be lost!

13 cursor.fetchone()

This method obtains the next row in the query result set, returns a single sequence, returns NONE when there is no more available data.

14 cursor.fetchmany([size=cursor.arraysize])

This method gets the next line of the query result set, returns a list.When there is no more available rows, an empty list is returned.This method attempts to get as many rows as specified by the Size parameter.

15 cursor.fetchall()

This routine acquires all (remaining) rows in the query result set, returns a list.When there is no line available, an empty list is returned.

Connect to the database

The following Python code shows how to connect to an existing database. If the database does not exist, it is created and a database object is returned.

#!/usr/bin/python

import sqlite3

conn = sqlite3.connect('test.db')

print "Opened database successfully";

Here, you can also copy the database name to a specific name: memory: , which creates a database in RAM. N ow, let's run the program above and create our database test in the .db. Y ou can change the path as needed. S ave the above code sqlite.py file and execute as follows. If the database is successfully created, the message shown below is displayed:

$chmod +x sqlite.py
$./sqlite.py
Open database successfully

Create a table

The following Python snippet will be used to create a table in a previously created database:

#!/usr/bin/python

import sqlite3

conn = sqlite3.connect('test.db')
print "Opened database successfully";

conn.execute('''CREATE TABLE COMPANY
       (ID INT PRIMARY KEY     NOT NULL,
       NAME           TEXT    NOT NULL,
       AGE            INT     NOT NULL,
       ADDRESS        CHAR(50),
       SALARY         REAL);''')
print "Table created successfully";

conn.close()

When the above program executes, it creates a COMPANY .db in the test table and displays the message shown below:

Opened database successfully
Table created successfully

INSERT operation

The following Python program shows how to create records in the COMPANY table created above:

#!/usr/bin/python

import sqlite3

conn = sqlite3.connect('test.db')
print "Opened database successfully";

conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
      VALUES (1, 'Paul', 32, 'California', 20000.00 )");

conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
      VALUES (2, 'Allen', 25, 'Texas', 15000.00 )");

conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
      VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )");

conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
      VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )");

conn.commit()
print "Records created successfully";
conn.close()

When the above program executes, it creates a given record in the COMPANY table and displays the following two lines:

Opened database successfully
Records created successfully

SELECT operation

The following Python program shows how to get and display records from the COMPANY table you created earlier:

#!/usr/bin/python

import sqlite3

conn = sqlite3.connect('test.db')
print "Opened database successfully";

cursor = conn.execute("SELECT id, name, address, salary  from COMPANY")
for row in cursor:
   print "ID = ", row[0]
   print "NAME = ", row[1]
   print "ADDRESS = ", row[2]
   print "SALARY = ", row[3], "\n"

print "Operation done successfully";
conn.close()

When the above procedure is executed, it produces the following results:

Opened database successfully
ID =  1
NAME =  Paul
ADDRESS =  California
SALARY =  20000.0

ID =  2
NAME =  Allen
ADDRESS =  Texas
SALARY =  15000.0

ID =  3
NAME =  Teddy
ADDRESS =  Norway
SALARY =  20000.0

ID =  4
NAME =  Mark
ADDRESS =  Rich-Mond
SALARY =  65000.0

Operation done successfully

UPDATE operation

The following Python code shows how to use the UPDATE statement to update any record, and then get and display the updated record from the COMPANY table:

#!/usr/bin/python

import sqlite3

conn = sqlite3.connect('test.db')
print "Opened database successfully";

conn.execute("UPDATE COMPANY set SALARY = 25000.00 where ID=1")
conn.commit
print "Total number of rows updated :", conn.total_changes

cursor = conn.execute("SELECT id, name, address, salary  from COMPANY")
for row in cursor:
   print "ID = ", row[0]
   print "NAME = ", row[1]
   print "ADDRESS = ", row[2]
   print "SALARY = ", row[3], "\n"

print "Operation done successfully";
conn.close()

When the above procedure is executed, it produces the following results:

Opened database successfully
Total number of rows updated : 1
ID =  1
NAME =  Paul
ADDRESS =  California
SALARY =  25000.0

ID =  2
NAME =  Allen
ADDRESS =  Texas
SALARY =  15000.0

ID =  3
NAME =  Teddy
ADDRESS =  Norway
SALARY =  20000.0

ID =  4
NAME =  Mark
ADDRESS =  Rich-Mond
SALARY =  65000.0

Operation done successfully

DELETE operation

The following Python code shows how to use the DELETE statement to delete any records, and then get and display the remaining records from the COMPANY table:

#!/usr/bin/python

import sqlite3

conn = sqlite3.connect('test.db')
print "Opened database successfully";

conn.execute("DELETE from COMPANY where ID=2;")
conn.commit
print "Total number of rows deleted :", conn.total_changes

cursor = conn.execute("SELECT id, name, address, salary  from COMPANY")
for row in cursor:
   print "ID = ", row[0]
   print "NAME = ", row[1]
   print "ADDRESS = ", row[2]
   print "SALARY = ", row[3], "\n"

print "Operation done successfully";
conn.close()

When the above procedure is executed, it produces the following results:

Opened database successfully
Total number of rows deleted : 1
ID =  1
NAME =  Paul
ADDRESS =  California
SALARY =  20000.0

ID =  3
NAME =  Teddy
ADDRESS =  Norway
SALARY =  20000.0

ID =  4
NAME =  Mark
ADDRESS =  Rich-Mond
SALARY =  65000.0

Operation done successfully