SQLite made Simple: Difference between revisions

From NSB App Studio
Jump to navigation Jump to search
 
(12 intermediate revisions by the same user not shown)
Line 1: Line 1:
== SQLite Overview ==
== SQLite Overview ==


[http://en.wikipedia.org/wiki/Sqlite SQLite] is a fast, popular and easy to use database. Its speed and easy of use make it a practical choice for use when you need an indexed file system for an app. Databases you create can be accessed, without change, on any platform SQLite supports. It is built into all mobile devices that AppStudio supports as well as the desktop.
[http://en.wikipedia.org/wiki/Sqlite SQLite] is a fast, popular and easy to use database. Its speed and easy of use make it a practical choice for use when you need an indexed file system for an app. Databases you create can be accessed, without change, on any platform SQLite supports. Using the [[Support_for_SQLite|SQLite (WASM) library]], it is usable on almost all platforms and browsers.


* Your app can create, update and delete SQLite databases.
* Your app can create, update and delete SQLite databases.
* Databases are kept in your app's private directory.
* Databases are kept in your app's localStorage.
* Apps cannot access each other's data for security purposes.
* Apps cannot access each other's data for security purposes.
* The exception is apps which are load from the same server.
* The exception is apps which are loaded from the same server.
* Databases cannot be directly imported or exported, once again, for security reasons. You can include an SQLite database with your app.
* Databases cannot be directly imported or exported, once again, for security reasons. You can include an SQLite database with your app.
* Databases can be imported or exported using SqlExport and SqlImport We will go in depth on SQLite in the next Section.
* Databases can be imported or exported using SqlExport and SqlImport.  


The maximum size of an SQLite database varies by OS and device. Here's an article with more information: http://www.html5rocks.com/en/tutorials/offline/quota-research/
We will go in depth on SQLite in the next Section.


== Asynchronous Results ==
The maximum size of an SQLite database varies by OS and device. It is limited by the maximum size of localStorage, generally about 5 or 10 megs.
 
* The results of calls to the database are returned asynchronously. That means that after a statement involving the database is executed, the next statement in the program is executed - even though the database operation may not be complete.
* When it finishes, it will call a success or fail function in your program.
* In the meantime, you can do other processing: update controls on the screen or do calculations.  
* Do not do a [[MsgBox]] statement while you are waiting for an SQL call to finish - you will lose the callback.
 
    console.log("Before doing call")
    sqlList="CREATE TABLE myData('name', 'age')"
    sql(DB, [sqlList, Success_Function, Fail_Function])
    console.log("After doing call")
    Function Success_Function(transaction, result)
      console.log("Success - result received"
    End function
    Function Fail_Function(transaction, result)
      console.log("Fail")
    End function
 
The result will be 3 messages, in this order, in the Chrome Debugger Console:
 
    Before doing call
    After doing call
    Success - result received


== Sample App ==
== Sample App ==
Line 53: Line 29:
* [[Sql]] sends an array of commands to SQLite for processing.
* [[Sql]] sends an array of commands to SQLite for processing.


<pre>
<tabber>
Dim DB
JavaScript=
<syntaxhighlight lang="JavaScript">
var DB;
 
function Main() {
  DB = SqlOpenDatabase("localStorage");
  sqlList = [];
  sqlList[0] = [
    "CREATE TABLE studentData('name', 'age', PRIMARY KEY('name') );",
    success,
    fail,
  ];
  Sql(DB, sqlList);
}
 
function success() {
  console.log("success");
}
 
function fail(error) {
  NSB.MsgBox(error);
}
</syntaxhighlight>
|-|
BASIC=
<syntaxhighlight lang="vb.net">Dim DB


Sub Main
Sub Main
   DB = SqlOpenDatabase("students.db","1.0","My Student Database")
   DB = SqlOpenDatabase("localStorage")
   sqlList=[]
   sqlList=[]
   sqlList[0]=["CREATE TABLE studentData('name', 'age', PRIMARY KEY('name') );", _
   sqlList[0]=["CREATE TABLE studentData('name', 'age', PRIMARY KEY('name') );", _
    success, fail]
  success, fail]
   Sql(DB, sqlList)
   Sql(DB, sqlList)
End Sub
End Sub


Sub success()
Sub success()
  console.log("success")
End Sub
End Sub


Sub fail()
Sub fail(error)
  MsgBox error
End Sub
End Sub
</pre>
</syntaxhighlight>
</tabber>


=== Save Button ===
=== Save Button ===
* Don't save anything if name is empty.
* Don't save anything if name is empty.
* INSERT INTO tells SQLite to add a record into the studentData table.
* INSERT INTO tells SQLite to add a record into the studentData table.
<pre>
<tabber>
JavaScript=
<syntaxhighlight lang="JavaScript">
btnSave.onclick = function () {
  if (txtName.value == "") {
    return;
  }
  sqlList = [];
  sqlList[0] = [
    "INSERT INTO studentData (name,age) VALUES (?,?)",
    [txtName.value, txtAge.value],
    success,
    fail,
  ];
  Sql(DB, sqlList);
};
</syntaxhighlight>
|-|
BASIC=
<syntaxhighlight lang="vb.net">
Function btnSave_onclick()
Function btnSave_onclick()
   If txtName.value="" Then Exit Function
   If txtName.value="" Then Exit Function
   sqlList = []
   sqlList = []
   sqlList[0]="INSERT INTO studentData (name,age) VALUES ('" & _
   sqlList[0]=["INSERT INTO studentData (name,age) VALUES (?,?)", _
    txtName.value & "','" & TxtAge.value & "')"
  [txtName.value, txtAge.value], success, fail]
   Sql(DB, sqlList)
   Sql(DB, sqlList)
End Function
End Function
</pre>
</syntaxhighlight>
</tabber>


=== Find Button ===
=== Find Button ===
Line 89: Line 113:
* The results (there could be more than one) are returned in an array.
* The results (there could be more than one) are returned in an array.
* If there are no rows in the array, nothing was found.
* If there are no rows in the array, nothing was found.
<pre>
<tabber>
JavaScript=
<syntaxhighlight lang="JavaScript">
btnFind.onclick = function () {
  sqlList = [];
  sqlList[0] = [
    "SELECT * FROM studentData WHERE name=?",
    txtFind.value,
    nameFound,
  ];
  Sql(DB, sqlList);
};
 
function nameFound(transaction, results) {
  if (results.rows.length > 0) {
    NSB.MsgBox(results.rows.item(0).name + " is " + results.rows.item(0).age);
  } else {
    NSB.MsgBox("Name not found");
  }
  txtName.value = results.rows.item(0).name;
  txtAge.value = results.rows.item(0).age;
}
</syntaxhighlight>
|-|
BASIC=
<syntaxhighlight lang="vb.net">
Function btnFind_onclick()
Function btnFind_onclick()
   sqlList=[]
   sqlList=[]
   sqlList[0]=["SELECT * FROM studentData WHERE name='" & _
   sqlList[0]=["SELECT * FROM studentData WHERE name=?", txtFind.value, nameFound]
    txtFind.value & "'", nameFound]
   Sql(DB, sqlList)
   Sql(DB, sqlList)
End Function
End Function


Function nameFound(transaction, results)
Function nameFound(transaction, results)
   If results.rows.length>0 Then
   If results.rows.length > 0 Then
     MsgBox results.rows.item(0).name & " is " & results.rows.item(0).age
     MsgBox results.rows.item(0).name & " is " & results.rows.item(0).age
   Else
   Else
     MsgBox "Name not found"
     MsgBox "Name not found"
   End If
   End If
  txtName.value = results.rows.item(0).name
  txtAge.value = results.rows.item(0).age
End Function
End Function
 
</syntaxhighlight>
</pre>
</tabber>


=== Delete Button ===
=== Delete Button ===
Line 111: Line 161:
* We call nameDeleted() on successful deletion.
* We call nameDeleted() on successful deletion.
* If the deletion is unsuccessful, nothing happens.
* If the deletion is unsuccessful, nothing happens.
<pre>
<tabber>
JavaScript=
<syntaxhighlight lang="JavaScript">
btnDelete.onclick = function () {
  sqlList = [];
  sqlList[0] = [
    "DELETE FROM studentData WHERE name=?",
    txtFind.value,
    nameDeleted,
  ];
  Sql(DB, sqlList);
  txtName.value = "";
  txtAge.value = "";
};
</syntaxhighlight>
|-|
BASIC=
<syntaxhighlight lang="vb.net">
Function btnDelete_onclick()
Function btnDelete_onclick()
   sqlList = []
   sqlList = []
   sqlList[0]=["DELETE FROM studentData WHERE name='" & _
   sqlList[0]=["DELETE FROM studentData WHERE name=?", txtFind.value, nameDeleted]
    txtFind.value & "'", nameDeleted]
   Sql(DB, sqlList)
   Sql(DB, sqlList)
  txtName.value = ""
  txtAge.value = ""
End Function
End Function


Line 122: Line 190:
   MsgBox txtFind.value & " Deleted"
   MsgBox txtFind.value & " Deleted"
End Function
End Function
 
</syntaxhighlight>
</pre>
</tabber>

Latest revision as of 16:14, 28 November 2025

SQLite Overview

SQLite is a fast, popular and easy to use database. Its speed and easy of use make it a practical choice for use when you need an indexed file system for an app. Databases you create can be accessed, without change, on any platform SQLite supports. Using the SQLite (WASM) library, it is usable on almost all platforms and browsers.

  • Your app can create, update and delete SQLite databases.
  • Databases are kept in your app's localStorage.
  • Apps cannot access each other's data for security purposes.
  • The exception is apps which are loaded from the same server.
  • Databases cannot be directly imported or exported, once again, for security reasons. You can include an SQLite database with your app.
  • Databases can be imported or exported using SqlExport and SqlImport.

We will go in depth on SQLite in the next Section.

The maximum size of an SQLite database varies by OS and device. It is limited by the maximum size of localStorage, generally about 5 or 10 megs.

Sample App

The following app saves names and ages to an SQLite database. A Find function can be used to locate existing entries. The current entry, once found, can be deleted.

Initialize

  • We need to create the database if it does not exist.
  • The variable DB is a global reference to the database.
  • SqlOpenDatabase creates the database. If it already exists, it does nothing.
  • CREATE TABLE is a command executed by SQLite.
  • It creates a table in the database.
  • If the table already exists, it does nothing.
  • Sql sends an array of commands to SQLite for processing.

var DB;

function Main() {
  DB = SqlOpenDatabase("localStorage");
  sqlList = [];
  sqlList[0] = [
    "CREATE TABLE studentData('name', 'age', PRIMARY KEY('name') );",
    success,
    fail,
  ];
  Sql(DB, sqlList);
}

function success() {
  console.log("success");
}

function fail(error) {
  NSB.MsgBox(error);
}

Dim DB

Sub Main
  DB = SqlOpenDatabase("localStorage")
  sqlList=[]
  sqlList[0]=["CREATE TABLE studentData('name', 'age', PRIMARY KEY('name') );", _
  success, fail]
  Sql(DB, sqlList)
End Sub

Sub success()
  console.log("success")
End Sub

Sub fail(error)
  MsgBox error
End Sub

Save Button

  • Don't save anything if name is empty.
  • INSERT INTO tells SQLite to add a record into the studentData table.

btnSave.onclick = function () {
  if (txtName.value == "") {
    return;
  }
  sqlList = [];
  sqlList[0] = [
    "INSERT INTO studentData (name,age) VALUES (?,?)",
    [txtName.value, txtAge.value],
    success,
    fail,
  ];
  Sql(DB, sqlList);
};

Function btnSave_onclick()
  If txtName.value="" Then Exit Function
  sqlList = []
  sqlList[0]=["INSERT INTO studentData (name,age) VALUES (?,?)", _
  [txtName.value, txtAge.value], success, fail]
  Sql(DB, sqlList)
End Function

Find Button

  • SELECT searches the table for matching records.
  • It calls the nameFound() function when it is done.
  • The results (there could be more than one) are returned in an array.
  • If there are no rows in the array, nothing was found.

btnFind.onclick = function () {
  sqlList = [];
  sqlList[0] = [
    "SELECT * FROM studentData WHERE name=?",
    txtFind.value,
    nameFound,
  ];
  Sql(DB, sqlList);
};

function nameFound(transaction, results) {
  if (results.rows.length > 0) {
    NSB.MsgBox(results.rows.item(0).name + " is " + results.rows.item(0).age);
  } else {
    NSB.MsgBox("Name not found");
  }
  txtName.value = results.rows.item(0).name;
  txtAge.value = results.rows.item(0).age;
}

Function btnFind_onclick()
  sqlList=[]
  sqlList[0]=["SELECT * FROM studentData WHERE name=?", txtFind.value, nameFound]
  Sql(DB, sqlList)
End Function

Function nameFound(transaction, results)
  If results.rows.length > 0 Then
    MsgBox results.rows.item(0).name & " is " & results.rows.item(0).age
  Else
    MsgBox "Name not found"
  End If
  txtName.value = results.rows.item(0).name
  txtAge.value = results.rows.item(0).age
End Function

Delete Button

  • DELETE removes matching records from the table
  • We call nameDeleted() on successful deletion.
  • If the deletion is unsuccessful, nothing happens.

btnDelete.onclick = function () {
  sqlList = [];
  sqlList[0] = [
    "DELETE FROM studentData WHERE name=?",
    txtFind.value,
    nameDeleted,
  ];
  Sql(DB, sqlList);
  txtName.value = "";
  txtAge.value = "";
};

Function btnDelete_onclick()
  sqlList = []
  sqlList[0]=["DELETE FROM studentData WHERE name=?", txtFind.value, nameDeleted]
  Sql(DB, sqlList)
  txtName.value = ""
  txtAge.value = ""
End Function

Function nameDeleted()
  MsgBox txtFind.value & " Deleted"
End Function