- SQLite Custom Sort Order In Python Example
- 1. Define A Custom Compare Function.
- 2. Create Custom Collation With The SQLite Database Connection Object’s create_collation(name, callable) Function.
- 3. SQLite Custom Sort Order In Python Example.
- Python - Sorting Data In SQLite3
- Getting started:
- Installing SQLite Browser
- Importing Modules
- Setting up the Main Frame
- Creating the Database Connection
- Designing the Layout
- Creating the Main Function
- Initializing the Application
SQLite Custom Sort Order In Python Example
We can use the order by child clause to sort the query results in the SQL statement, but it can only sort the query results by the simple and fixed order. How about ordering the query results in a complex sort order? This article will tell you how to implement it in the SQLite database with python.
1. Define A Custom Compare Function.
- First, you should create a python function, this function contains 2 input parameters.
- You should compare the 2 input parameters according to your needs, and return an integer value -1, 0, 1, below is an example.
''' This function will compare two string value. First it will convert the string to integer value, then it will compare the two integer value and return related result. ''' def custom_order_by_int_value(str1, str2): str1_int = int(str1[1:-1]) str2_int = int(str2[1:-1]) if(str1_int > str2_int): return 1 elif(str1_int < str2_int): return -1 else: return 0
2. Create Custom Collation With The SQLite Database Connection Object’s create_collation(name, callable) Function.
- The SQLite database connection object provides a create_collation(name, callable) function.
- The first parameter name is the custom collation name that you defined, it should be a string.
- The second parameter callable is the python function that you defined in step 1, in this example the custom python function is custom_order_by_int_value.
- The below source code will create the custom collation with the SQLite database connection object, the collation name is ‘order_by_int_value’, the collation callable python function name is custom_order_by_int_value.
conn.create_collation('order_by_int_value', custom_order_by_int_value)
sql = "select * from " + table_name + " order by passwd collate order_by_int_value"
3. SQLite Custom Sort Order In Python Example.
- In this example, the SQLite database name is ‘test-sqlite.db’, the table name is ‘user_account’. Below is the table data, we can see the passed field value are all integer strings.
id user_name passwd email 14 jerry [97531] [email protected] 15 tom [0000888] [email protected]
import sqlite3 import com.dev2qa.example.sqlite.util db_name = 'test-sqlite.db' table_name = 'user_account' ''' This function will compare two string value. First it will convert the string to integer value, then it will compare the two integer value and return related result. ''' def custom_order_by_int_value(str1, str2): str1_int = int(str1[1:-1]) str2_int = int(str2[1:-1]) if(str1_int > str2_int): return 1 elif(str1_int < str2_int): return -1 else: return 0 ''' This function will call the above custom order function in the order by clause. ''' def custom_sort_order(): # get database connection to the SQLite database. conn = sqlite3.connect(db_name) # create collation with the custom order by function. conn.create_collation('order_by_int_value', custom_order_by_int_value) # get the database cursor object. cursor = conn.cursor() # create the sql statement with the collate clause. sql = "select * from " + table_name + " order by passwd collate order_by_int_value" # execute the above sql statement. cursor.execute(sql) # loop in the cursor to get all the rows. for row in cursor: # print out the row. print(row) # commit the database connection. conn.commit() # close the cursor object. cursor.close() # close the database connection object. conn.close() if __name__ == '__main__': custom_sort_order()
(15, 'tom', '[0000888]', '[email protected]') (14, 'jerry', '[97531]', '[email protected]')
Python - Sorting Data In SQLite3
In this tutorial we will create a Sorting Data In SQLite3 using Python. This code will sort all the data in the SQLite database in TreeView when user click the sorting button. The code use tkinter module to create a layout and widgets that can call python functions. When a function is called it will immediately sort the data whether ASCENDING or DESCENDING in TreeView by SQLite SELECT query and adding ORDER BY parameter. We will be using Python because it has a design philosophy which emphasizes code readability. That's why python is very easy to use especially for beginners who just started programming. It is very easy to learn the syntax emphasizes readability and it can reduces time consuming in developing..
Getting started:
First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.
Installing SQLite Browser
After you installed Python, we will now then install the SQLite, here's the link for the DB Browser for SQLite http://sqlitebrowser.org/.
Importing Modules
After setting up the installation and the database, run the IDLE and click file and then new file. After that a new window will appear containing a black file this will be the text editor for the python. Then copy code that I provided below and paste it inside the IDLE text editor.
Setting up the Main Frame
After importing the modules, we will now then create the main frame for the application. To do that just copy the code below and paste it inside the IDLE text editor.
Creating the Database Connection
Then after setting up the design we will now create the database function. To do that just simply copy the code below and paste it inside the IDLE text editor, then save it as connection.py.
Designing the Layout
After creating the Main Frame we will now add some layout to the application. Just kindly copy the code below and paste it inside the IDLE text editor.
Creating the Main Function
This is where the code that contains the main funcitions. This code will sort all the SQLite data in TreeView when the button is clicked. To do that just copy and write these blocks of code.
Initializing the Application
After finishing the function save the application as index.py. This function will run the code and check if the main application is initialized properly. To do that copy the code below and paste it inside the IDLE text editor.
There you have it we just created a Sorting Data In SQLite3 Using Python. I hope that this simple tutorial help you for what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!!