SQLite extension (SPONSORED!)

extension

(Carlos Pedroza) #1

PedrozaSQLite

Hello! Here I present to you my second extension ever created! It is an extension to access the local SQLite database!

Background

I know there is already a few extensions with this functionality, but here are the reasons why I made it:

  • First of all, thanks to AppInventor and all its distributions I took my first steps on how to code. Later, I thought about creating extensions and I found that I really like Java and the whole process of thinking and trying to run it correctly. So I took my chances and made my first extension that I published it here in Thunkable (Polyline Tools).
  • I knew that I wanted more, and decided to make one of the extensions I always wanted to have but couldn’t afford it.
  • My goal is to let other people like me use this extension, but always remembering the true meaning of AppInventor that is learning how to code. So if you feel like you can take the next step, I encourage you to try it. It’s really fun!
  • Also, by letting other people sponsor this extension I would have the opportunity to earn enough money to create my Developer Account.

So this is it! I hope you find this useful and if you find how to make it better, please let me know so I can learn from it!


For reference on how to write SQLite statements, I recommend for a good quick start TutorialPoint.com and SoloLearn’s SQL Fundamentals.


For other options availables:

  • Taifun’s SQLite Extension - Link (since Aug 11th, 2016).
  • Andrés Cotes’ SQLite Extension - Link (since Oct 2nd, 2017).
  • Juan Ruvalcaba’s SQLite Extension - Link (since September 8th, 2017).

Description

Tool developed by Carlos Pedroza to access the application’s SQlite database based on SQLite Android Developer’s Reference.


FEATURES

  • SQL Statements executes asynchronously, very useful in large databases.
  • Good practices to avoid as possible SQL Injections.
  • Opportunity to use rawQuery and write SQL statements.
  • Compile a statement to reuse it later (on next release).
  • Query result in a list for easy use.

DISADVANTAGES

  • Not able to export and import databases as a file .sqlite (I don’t know how to do it, yet).

Methods

  • AfterExecution: Event handler after the SQL statement is executed, returns whether the execution was succesfully executed.
    image

  • AfterQuery: Event handler after the ExecuteRawQuery or Query is executed and returns a list with the selected data and number of records.
    image

  • ErrorOcurred: Event handler when an error ocurred, returns a string with a message from the error.
    image

  • Query: Executes pre-compiled QUERY statement with specified parameters. Parameters: 1) String table: Name of the table. 2) YailList columns: List of which columns to return, passing an empty list will return all columns. 3) String selection: Filter declaring which rows to return, formatted as an SQL WHERE clause, passing an empty string will return all rows. 4) YailList selectionArgs: List with the arguments that will replace onto ‘?’ in the selection filter. 5) String groupBy: A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself), passing an empty string will cause the row to not be grouped. 6) String having: A filter declare which row groups to include if row grouping is being used, passing an empty string will cause all row groups to be included. 7) String orderBy: How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself), passing an empty string will use the default sort order (unordered). 8) String limit: Limits the number of rows returned by the query, formatted as LIMIT clause, passing an empty string denotes no LIMIT clause. Return: The result query is available in the AfterQuery event handler.
    image

  • Insert: Executes pre-compiled INSERT statement with specified parameters. Parameters: 1) String table: Name of the table. 2) YailList columns: List with the columns that will contain the data to be inserted in the database. 3) YailList values: List with the data to be inserted in the database. Returns the row ID of the newly inserted row, or -1 if an error occurred.
    image

  • Replace: Executes pre-compiled REPLACE OR INSERT INTO statement with specified parameters. Parameters: 1) String table: Name of the table. 2) YailList columns: List with the columns that will contain the data to be replaced in the database. 3) YailList values List with the data to be replaced in the database. Returns the row ID of the newly replaced row, or -1 if an error occurred.
    image

  • Update: "Executes pre-compiled UPDATE statement with specified parameters. Parameters: 1) String table: Name of the table. 2) YailList columns List with the columns that will contain the data to be inserted in the database. 3) YailList values List with the data to be inserted in the database. 4) String whereClause: optional WHERE clause to apply when updating, leave an empty string to update all rows. Include ?s, which will be updated by the values from whereArgs. 5) YailList whereArgs: List with the columns that will contain the data to be updated in the database. Returns the row ID of the newly inserted row, or -1 if an error occurred.
    image

  • Delete: Executes pre-compiled DELETE statement with specified parameters. Parameters: 1) String table: Name of the table. 2) String whereClause: Optional WHERE clause to apply when deleting (Example: ‘ID = ?’), pasing an empty a string will delete all rows. 3) List whereArgs: List with arguments for the WHERE clause. These arguments will be replaced by ‘?’ in the whereClause. Returns the number of rows affected if a whereClause is passed in, 0 otherwise.
    image

  • SingleSQL: Execute a Single SQL Statement asynchronously and returns whether the transaction was succesful in the AfterExecution Event Handler. Use it when returned data isn’t needed. Parameters: String sql.
    image

  • MultipleSQL: Execute Multiple SQL Statement asynchronously and returns whether the transaction was succesful in the AfterExecution Event Handler. Use it when returned data isn’t needed. Parameters: List of SQL statements.
    image

  • RawQuery: Executes the provided rawQuery Statement asynchronously. Returns a YailList with the selected data and number of records in the AfterQuery Event. Parameters: 1)String SQL statement. 2) List selectionArgs: List with the arguments that will replace ‘?’ in where clause in the query, to prevent SQL injections.
    image

  • GetPath: Returns the path to the database.
    image

  • ClearDatabase: Clears the database to version 1. Use only while developing, this shouldn’t be used on production.
    image

  • ReturnHeader:
    Returns whether the header row should be returned in the result of a Select statement.
    image
    Specifies whether the header row should be returned in the result of a Select statement.
    image

  • SupressToast:
    Returns whether Success Toast should be suppressed.
    image
    Specifies whether Success Toast should be suppressed.
    image


Best Practices

In order to avoid SQL Injections and use pre-compiled statements, it is a good practice to use this blocks to SELECT, INSERT, UPDATE, REPLACE and DELETE.
image

On the other hand, these block are useful for executing a single SQL statement that is NOT a SELECT or any other SQL statement that returns data (INSERT, UPDATE, REPLACE or DELETE). It has no means to return any data (such as the number of affected rows). Statements like CREATE or DROP table / trigger / view / index / virtual table, ALTER TABLE, REINDEX, RELEASE, SAVEPOINT and PRAGMA are very good options to use these block for.
image

When using rawQuery (using it a lot will cause performance issues because it compiles it over and over again) use the selectionArgs to provide the arguments that will replace ‘?’ in the where clause to prevent SQL injections. For example: SELECT * FROM table_name WHERE ID=?, the arguments in selectionArgs will replace all ?.
image


Price

This extension has been sponsored by @Peter and Diego Marino!

If you find this useful, you still can donate!
Donation Link: http://paypal.me/DrCarlosPedroza


Downloads

.AIX: com.pedroza.PedrozaSQLite.aix (23,4 KB)
.java Available at Github
Test .APK: PedrozaSQLite.apk (1,6 MB)
Test .AIA: PedrozaSQLite.aia (32,9 KB)


Changelog

  • October 9, 2017 - Initial release.

UPCOMING:

  • More functions like CompileStatements in order to reuse precompiled statements.
  • Video tutorial :smiley:
  • Video tutorial on how to write SQLite statements

Best Regards from :venezuela:,
Carlos Pedroza


(Sander Jochems) #2

Great job! You realy took your time to write the best extension post ever!


#4

If i test your apk and insert records by repeatedly pressing the insert button fast and go to the playground it keeps displaying a banner “Inserted ID = …” with the number in the middle of the screen.

Everything is working. Great work Carlos :+1:

I hope you find a way to import an database so that you can easily add it to the assets of your app.


(Ben) #5

Quick question, by Java code, what do you mean? If I buy/donate ext for 2€, I get AIX & Java code?


#6

He means if he gets 25 dollars in total he will free the sourcecode.


(Ben) #7

Didn’t see that :slight_smile:


#8

Carlos, i paypalled you the money to buy yourself a Google Developers Account. Good luck with your programming endeavours. :+1:


#9

hi,peter, you are a good man!
With your help,I believe he can make more efforts to make better achievements.


(Diego Barreiro Pérez) #10

This extension will be definitely integrated in Makeroid! :+1:


(Ben) #11

But make sure, to give credits for @CarlosPedroza27, as he developed the extension and you have used it.


#12

Carlos already gave permission to the Makeroid developers to use his code in Makeroid.


(Diego Barreiro Pérez) #13

I’ve already been talking with him for some days about the extension :wink:


(Carlos Pedroza) #14

That’s correct, and that is my goal when liberating the source code: Contribute to the AppInventor and all its distributions community.


#15

I have merged this extension into a Makeroid component; It’ll be available in the next update. Thank you @CarlosPedroza27, great extension!


split this topic #16

A post was split to a new topic: YAIL error when compiling


(Luca) #17

This has been a known extension posted in other distributors too and a very good one.
I am glad to see it embedded in Makeroid.

I am failing to use it with multiple WHERE, GROUP BY & ORDER BY CRITERIA in the pre-compiled statements.
No problem at using raw queries to get the results I need.

Could anyone post a block example for
call PedrozaSQLite1. Query
call PedrozaSQLite1.Update
call PedrozaSQLite1.Delete

blocks with multiple criteria???

Thank you in advance!!


(Mauricio Zaccaro Neto) #18

Como eu consigo essa extensão?
Aqui diz que o Link não existe.


(rbnet) #19

This extension is included with Kodular. It is the SQL component, in Storage.


(Mauricio Zaccaro Neto) #20

But, the extension included in Kodular does not have the option “Import / FileName” or “ImportDatabase / FileName”. With the basic options you have, I did not understand how to open a database :expressionless:


(rbnet) #21

The original extension doesn’t have these features either.

You can create the DB on the fly, using the SingleSQL method. Then you can’t export it easily. For import/export methods you can try these two extensions: