sqlite3 module provides a Python interface to use and manage SQLite database. In this article we will look on how we can use Python functions in SQL statements when querying an SQLite database.
SQL allows function to be used in statements to process data before it is returned. Particularly, SQL functions are allowed either in the WHERE
clause of the SELECT
statement or in column lists.
To allow Python functions to be used in SQL queries, we will need to register that function using the create_function()
method of connection objects.
Basic example
Consider if we have an SQLite database for storing student details. The following example creates the students
database:
Register a function
Consider if we want to retrieve the students from the database with the student names being capitalized and the name of school in upper case and without updating the columns in database. We can define and register two functions as shown below.
In the above example we defined and registered two functions transform_upper
and capitalize
, we then used the functions in the SELECT
query to capitalize the student names and transform the name of the school to uppercase. Of course, SQL provides native functions for basic operations such as UPPER
to capitalize a value.
The conn.create_function()
creates an sql function from a Python function. Its basic syntax is shown below:
conn.create_function(name, nargs, func)
copy
The name
parameter is the name of the function as it will appear in the sql queries.
The nargs
parameter is the number of arguments taken by the function.
The func
parameter is the actual Python function.