Python SQLite connection.close() Function



The python connection.close() function is used to close the database connection in python and java programming languages. This function is useful for resource management and also to handle files and memory for the connection database.

In SQLite, a connection refers to an active link between the application and database. This connection allows us to execute SQL commands and queries in the database.

Syntax

Following is the syntax for the connection.close() function.

conn.close()

Parameters

This function doesn't take any parameters.

Return Value

This connection.rollback() function has no return value.

Example 1

The connection.close() function doesn't produce output directly, then this function specifies that the connection to the database is closed.

Here, is a basic example using the connection.close() function.

import sqlite3
connection = sqlite3.connect('res.db')
connection.close()

Output

By running the above code, this program simply creates and closes the database without any output.

Example

Consider the following EMPLOYEES table which stores employees ID, Name, Age, Salary, City and Country −

IDNameAgeSalaryCityCountry
1Ramesh322000.00MarylandUSA
2Mukesh405000.00New YorkUSA
3Sumit454500.00MuscatOman
4Kaushik252500.00KolkataIndia
5Hardik293500.00BhopalIndia
6Komal383500.00SaharanpurIndia
7Ayush253500.00DelhiIndia

Example 2

In the below example, we are deleting the rows from the given employees table using connection.close() function.

import sqlite3
connection = sqlite3.connect('res.db')
cursor = connection.cursor()
cursor.execute("DELETE FROM employees WHERE ID IN (2, 3, 4, 5, 7)")
connection.commit()
connection.close()

Output

We will get the output as follows −

IDNameAgeSalaryCityCountry
1Ramesh322000.00MarylandUSA
6Komal383500.00SaharanpurIndia

Example 3

In the below example we are updating the salaries of all employees to 3000 using connection.close() function.

import sqlite3
connection = sqlite3.connect('res.db')
cursor = connection.cursor()
cursor.execute("UPDATE Employees SET Salary = 3000.00 WHERE ID IN (1, 2, 3, 4, 5, 6, 7)")
connection.commit()
connection.close()

Output

The result is obtained as follows −

IDNameAgeSalaryCityCountry
1Ramesh323000.00MarylandUSA
2Mukesh403000.00New YorkUSA
3Sumit453000.00MuscatOman
4Kaushik253000.00KolkataIndia
5Hardik293000.00BhopalIndia
6Komal383000.00SaharanpurIndia
7Ayush253000.00DelhiIndia
python_modules.htm