The Wayback Machine - https://web.archive.org/web/20241002010921/https://www.geeksforgeeks.org/how-to-store-python-functions-in-a-sqlite-table/
Open In App

How to store Python functions in a Sqlite table?

Last Updated : 01 Oct, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

SQLite is a relational database system contained in a C library that works over syntax very much similar to SQL. It can be fused with Python with the help of the sqlite3 module. The Python Standard Library sqlite3 was developed by Gerhard Häring. It delivers an SQL interface compliant with the DB-API 2.0 specification described by PEP 249. 

To use this module and establish the connection with database:- 

      1. Import sqlite3 module and create the object representing the database.

import sqlite3
conn = sqlite3.connect('function.db')

       2. To execute SQL commands, construct a cursor object and call the execute() method.

c = conn.cursor()
c.execute('''CREATE TABLE student
             (Number REAL,stud_name TEXT)''')

Note: In Order to track the operations on a database level we need to download the SQLite browser database.

Steps to store Python function in SQLite table: 

  • Step 1) Import sqlite3 and create the object of database .

Python3




import sqlite3
conn = sqlite3.connect('function.db')


Here we have imported sqlite3 module, and We have initialized the database function.db. This instruction will create the database if the database doesn’t exist and if the database having the same name as defined exist than it will move further. 

  • Step 2) Create a Cursor object and call its execute() method to create table.

Python3




c = conn.cursor()
c.execute('''CREATE TABLE pyfuction
             (func_defination TEXT)''')


After initializing the database we have to create the cursor object using conn.cursor(). The cursor allows us to execute the SQL commands.

  • Step 3) Write Function in below syntax.

Python3




code = """ def gfg(): print("GeeksforGeeks") """


Since we have to store the function definition inside the table, we have to write function in the above syntax. 

  • Step 4) Insert function into pyfunction table.

Python3




c.execute("INSERT INTO pyfuction (func_defination) VALUES (?)",
          (code,))
conn.commit()


The SQL command “INSERT INTO pyfuction (func_defination) VALUES (?)”, (code) inserts the value of variable code inside the table pyfunction in the form of text. Then use the commit() method to save the changes.

Below are some examples store Python functions in a Sqlite table?

Example 1: Storing gfg() function in sqlite table named pyfunction.

Python3




# Importing required library
import sqlite3
  
# Initializing the database
conn = sqlite3.connect('function.db')
  
# Creating cursor object
c = conn.cursor()
  
# Creating table
c.execute('''CREATE TABLE pyfuction
             (func_defination TEXT)''')
  
# Storing a python function in the Sqlite table
code = """ def gfg(): print("GeeksforGeeks")"""
c.execute("INSERT INTO pyfuction (func_defination) VALUES (?)",
          (code))
  
# Terminating the transaction
conn.commit()


Output:

Example 2: Here is another example of storing a function named add() in the pyfunction table.

Python3




# Importing required library
import sqlite3
  
# Initializing the database
conn = sqlite3.connect('function.db')
  
# Creating cursor object
c = conn.cursor()
  
# Creating table
c.execute('''CREATE TABLE pyfuction
             (func_defination TEXT)''')
  
# Storing a python function in the Sqlite table
code = """ def add(): print((10+20)/2)"""
c.execute("INSERT INTO pyfuction (func_defination) VALUES (?)",
          (code,))
  
# Displaying Content of the table
c.execute("SELECT * FROM pyfuction;")
print(c.fetchall())
  
# Terminating the transaction
conn.commit()


Output:

Example 3: Storing two functions, maximum() and gfg() in pyfunction table.

Python3




# Importing required library
import sqlite3
  
# Initializing the database
conn = sqlite3.connect('function.db')
  
# Creating cursor object
c = conn.cursor()
  
# Creating table
c.execute('''CREATE TABLE pyfuction
             (func_defination TEXT)''')
  
# Storing a python function in the Sqlite table
def1 = """ def maximum(): print(max(2,5))"""
c.execute("INSERT INTO pyfuction (func_defination) VALUES (?)",
          (def1,))
  
# Storing another python function in the Sqlite table
def2 = """ def gfg(): print("GeeksforGeeks")"""
c.execute("INSERT INTO pyfuction (func_defination) VALUES (?)",
          (def2,))
  
# Displaying Content of the table
c.execute("SELECT * FROM pyfuction;")
print(c.fetchall())
  
# Terminating the transaction
conn.commit()


Output:



Previous Article
Next Article

Similar Reads

Store Google Sheets data into SQLite Database using Python
In this article, we are going to store google sheets data into a database using python. The first step is to enable the API and to create the credentials, so let's get stared. Enabling the APIs and creating the credentialsGo to Marketplace in Cloud Console.Click on ENABLE APIS AND SERVICESThen Search for Google Drive API and enable itThen go to the
5 min read
GUI to generate and store passwords in SQLite using Python
In this century there are many social media accounts, websites, or any online account that needs a secure password. Often we use the same password for multiple accounts and the basic drawback to that is if somebody gets to know about your password then he/she has the access to all your accounts. It is hard to remember all the distinct passwords. We
8 min read
Python SQLite - Create Table
In this article, we will discuss how can we create tables in the SQLite database from the Python program using the sqlite3 module. In SQLite database we use the following syntax to create a table: CREATE TABLE database_name.table_name( column1 datatype PRIMARY KEY(one or more columns), column2 datatype, column3 datatype, ..... columnN datatype ); N
1 min read
How to Delete a Specific Row from SQLite Table using Python ?
In this article, we will discuss how to delete of a specific row from the SQLite table using Python. In order to delete a particular row from a table in SQL, we use the DELETE query, The DELETE Statement in SQL is used to delete existing records from a table. We can delete a single record or multiple records depending on the condition we specify in
3 min read
How to Update all the Values of a Specific Column of SQLite Table using Python ?
In this article, we are going to update all the values of a specific column of a given SQLite table using Python. In order to update all the columns of a particular table in SQL, we use the UPDATE query. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple colu
3 min read
Python SQLite - DROP Table
In this article, we will discuss the DROP command in SQLite using Python. But first, let's get a brief about the drop command. DROP is used to delete the entire database or a table. It deleted both records in the table along with the table structure. Syntax: DROP TABLE TABLE_NAME; For dropping table, we will first create a database and a table in i
2 min read
Python SQLite - Deleting Data in Table
In this article, we will discuss how we can delete data in the table in the SQLite database from the Python program using the sqlite3 module. In SQLite database we use the following syntax to delete data from a table: DELETE FROM table_name [WHERE Clause] To create the database, we will execute the following code: C/C++ Code import sqlite3 # Connec
2 min read
How to Count the Number of Rows of a Given SQLite Table using Python?
In this article, we will discuss how we can count the number of rows of a given SQLite Table using Python. We will be using the cursor_obj.fetchall() method to do the same. This method fetches all the rows of a query result. It returns all the rows as a list of tuples. An empty list is returned if there is no record to fetch. To create the database
2 min read
How to Alter a SQLite Table using Python ?
In this article, we will discuss how can we alter tables in the SQLite database from a Python program using the sqlite3 module. We can do this by using ALTER statement. It allows to: Add one or more column to the tableChange the name of the table.Adding a column to a table The syntax of ALTER TABLE to add a new column in an existing table in SQLite
3 min read
How to Import a CSV file into a SQLite database Table using Python?
In this article, we are going to discuss how to import a CSV file content into an SQLite database table using Python. Approach:At first, we import csv module (to work with csv file) and sqlite3 module (to populate the database table).Then we connect to our geeks database using the sqlite3.connect() method.At this point, we create a cursor object to
3 min read
Check if Table Exists in SQLite using Python
In this article, we will discuss how to check if a table exists in an SQLite database using the sqlite3 module of Python. In an SQLite database, the names of all the tables are enlisted in the sqlite_master table. So in order to check if a table exists or not we need to check that if the name of the particular table is in the sqlite_master table or
2 min read
Python SQLite - Select Data from Table
In this article, we will discuss, select statement of the Python SQLite module. This statement is used to retrieve data from an SQLite table and this returns the data contained in the table. In SQLite the syntax of Select Statement is: SELECT * FROM table_name; * : means all the column from the table To select specific column replace * with the col
3 min read
Python - Create or Redefine SQLite Functions
The SQLite does not have functions or stored procedure language like MySQL. We cannot create stored functions or procedures in SQLite. That means the CREATE FUNCTION or CREATE PROCEDURE does not work in SQLite. In SQLite instead of CREATE FUNCTION or CREATE PROCEDURE we have SQLite’s C API which allows us to create our own user-defined functions, o
3 min read
Using SQLite Aggregate functions in Python
In this article, we are going to see how to use the aggregate function in SQLite Python. An aggregate function is a database management function that groups the values of numerous rows into a single summary value. Average (i.e., arithmetic mean), sum, max, min, Count are common aggregation functions. SQLite provides us with many aggregate functions
4 min read
Python SQLite - Insert Data
In this article, we will discuss how can we insert data in a table in the SQLite database from Python using the sqlite3 module. The SQL INSERT INTO statement of SQL is used to insert a new row in a table. There are two ways of using the INSERT INTO statement for inserting rows: Only values: The first method is to specify only the value of data to b
3 min read
SQL using Python and SQLite | Set 2
Databases offer numerous functionalities by which one can manage large amounts of information easily over the web, and high-volume data input and output over a typical file such as a text file. SQL is a query language and is very popular in databases. Many websites use MySQL. SQLite is a "light" version that works over syntax very much similar to S
3 min read
Python SQLite - Update Data
In this article, we will discuss how we can update data in tables in the SQLite database using Python - sqlite3 module. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement. Syntax: UPDATE table_name SET col
7 min read
How to Create a Backup of a SQLite Database using Python?
In this article, we will learn How to Create a Backup of an SQLite Database using Python. To Create a Backup of an SQLite Database using Python, the required modules are SQLite3 and IO. First, let's create the original database to do that follow the below program: C/C++ Code import sqlite3 import io from sqlite3 import Error def SQLite_connection()
2 min read
Introduction to SQLite in Python
Databases offer numerous functionalities by which one can manage large amounts of information easily over the web and high-volume data input and output over a typical file such as a text file. SQL is a query language and is very popular in databases. Many websites use MySQL. SQLite is a "light" version that works over syntax very much similar to SQ
3 min read
Python SQLite - Update Specific Column
In this article, we will discuss how to update a specific column of a table in SQLite using Python. In order to update a particular column in a table in SQL, we use the UPDATE query. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE stat
3 min read
Python SQLite - JOIN Clause
In this article, we discuss the JOIN clause in SQLite using the sqlite3 module in Python. But at first let's see a brief about join in SQLite. Join Clause A JOIN clause combines the records from two tables on the basis of common attributes. The different types of joins are as follows: INNER JOIN (OR JOIN) - Gives the records that have common attrib
5 min read
Creating a sqlite database from CSV with Python
Prerequisites: PandasSQLite SQLite is a software library that implements a lightweight relational database management system. It does not require a server to operate unlike other RDBMS such as PostgreSQL, MySQL, Oracle, etc. and applications directly interact with a SQLite database. SQLite is often used for small applications, particularly in embed
2 min read
Python SQLite - CRUD Operations
In this article, we will go through the CRUD Operation using the SQLite module in Python. CRUD Operations The abbreviation CRUD expands to Create, Read, Update and Delete. These four are fundamental operations in a database. In the sample database, we will create it, and do some operations. Let's discuss these operations one by one with the help of
4 min read
SQLite Datatypes and its Corresponding Python Types
SQLite is a C-language-based library that provides a portable and serverless SQL database engine. It has a file-based architecture; hence it reads and writes to a disk. Since SQLite is a zero-configuration database, no installation or setup is needed before its usage. Starting from Python 2.5.x, SQLite3 comes default with python. In this article, w
3 min read
How to connect to SQLite database that resides in the memory using Python ?
In this article, we will learn how to Connect an SQLite database connection to a database that resides in the memory using Python. But first let brief about what is sqlite. SQLite is a lightweight database software library that provides a relational database management system. Generally, it is a server-less database that can be used within almost a
3 min read
Python SQLite - ORDER BY Clause
In this article, we will discuss ORDER BY clause in SQLite using Python. The ORDER BY statement is a SQL statement that is used to sort the data in either ascending or descending according to one or more columns. By default, ORDER BY sorts the data in ascending order. DESC is used to sort the data in descending order.ASC to sort in ascending order.
3 min read
Python SQLite - LIMIT Clause
In this article, we are going to discuss the LIMIT clause in SQLite using Python. But first, let's get a brief about the LIMIT clause. If there are many tuples satisfying the query conditions, it might be resourceful to view only a handful of them at a time. LIMIT keyword is used to limit the data given by the SELECT statement. Syntax: SELECT colum
2 min read
Change SQLite Connection Timeout using Python
In this article, we will discuss how to change the SQLite connection timeout when connecting from Python. What is a connection timeout and what causes it? A connection timeout is an error that occurs when it takes too long for a server to respond to a user's request. Connection timeouts usually occur when there are multiple active connections to a
3 min read
How to Show all Columns in the SQLite Database using Python ?
In this article, we will discuss how we can show all columns of a table in the SQLite database from Python using the sqlite3 module. Approach:Connect to a database using the connect() method.Create a cursor object and use that cursor object created to execute queries in order to create a table and insert values into it.Use the description keyword o
3 min read
Python SQLite - Creating a New Database
In this article, we will discuss how to create a Database in SQLite using Python. Creating a Database You do not need any special permissions to create a database. The sqlite3 command used to create the database has the following basic syntax Syntax: $ sqlite3 <database_name_with_db_extension> The database name must always be unique in the RD
3 min read
Article Tags :
Practice Tags :