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 −
| ID | Name | Age | Salary | City | Country |
|---|---|---|---|---|---|
| 1 | Ramesh | 32 | 2000.00 | Maryland | USA |
| 2 | Mukesh | 40 | 5000.00 | New York | USA |
| 3 | Sumit | 45 | 4500.00 | Muscat | Oman |
| 4 | Kaushik | 25 | 2500.00 | Kolkata | India |
| 5 | Hardik | 29 | 3500.00 | Bhopal | India |
| 6 | Komal | 38 | 3500.00 | Saharanpur | India |
| 7 | Ayush | 25 | 3500.00 | Delhi | India |
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 −
| ID | Name | Age | Salary | City | Country |
|---|---|---|---|---|---|
| 1 | Ramesh | 32 | 2000.00 | Maryland | USA |
| 6 | Komal | 38 | 3500.00 | Saharanpur | India |
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 −
| ID | Name | Age | Salary | City | Country |
|---|---|---|---|---|---|
| 1 | Ramesh | 32 | 3000.00 | Maryland | USA |
| 2 | Mukesh | 40 | 3000.00 | New York | USA |
| 3 | Sumit | 45 | 3000.00 | Muscat | Oman |
| 4 | Kaushik | 25 | 3000.00 | Kolkata | India |
| 5 | Hardik | 29 | 3000.00 | Bhopal | India |
| 6 | Komal | 38 | 3000.00 | Saharanpur | India |
| 7 | Ayush | 25 | 3000.00 | Delhi | India |
python_modules.htm