Download the free trial version
Basic4android Video
Features
Tutorials and manuals
Showcase
Screenshots

Go Back   Android Development Forum - Basic4android > Basic4android > Basic4android Getting started & Tutorials
Documentation Wiki Register Members List B4P Search Today's Posts Mark Forums Read

Basic4android Getting started & Tutorials Android development starts here. Please do not post questions in this sub-forum.

SQL tutorial

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 12-02-2010, 03:04 PM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 15,689
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default SQL tutorial

This tutorial covers the SQL library and its usage with Basic4android.
There are many general SQL tutorials that cover the actual SQL language. If you are not familiar with SQL it is recommended to start with such a tutorial.
SQL Introduction

A new code module is available named DBUtils. It contains methods for common tasks which you can use and also learn from the code.

Android uses SQLite which is an open source SQL implementation.
Each implementation has some nuances. The following two links cover important information regarding SQLite.
SQLite syntax: Query Language Understood by SQLite
SQLite data types: Datatypes In SQLite Version 3

SQL in Basic4android
The first step is to add a reference to the SQL library. This is done by going to the Libraries tab and checking SQL.
There are two types in this library.
An SQL object gives you access to the database.
The Cursor object allows you to process queries results.

Usually you will want to declare the SQL object as a process global object. This way it will be kept alive when the activity is recreated.

SQLite stores the database in a single file.
When we initialize the SQL object we pass the path to a database file (which can be created if needed).
Code:
Sub Process_Globals
    
Dim SQL1 As SQL
End Sub

Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
    
If FirstTime Then 
        SQL1.Initialize(
File.DirDefaultExternal, "test1.db"True)
    
End If
    CreateTables
    FillSimpleData
    LogTable1
    InsertManyRows
    
Log("Number of rows = " & SQL1.ExecQuerySingleResult("SELECT count(*) FROM table1"))
    
    InsertBlob 
'stores an image in the database.
    ReadBlob 'load the image from the database and displays it.
End Sub
The SQL1 object will only be initialized once when the process starts.
In our case we are creating it in the sd card. The last parameter (CreateIfNecessary) is True so the file will be created if it doesn't exist.

There are three types of methods that execute SQL statements.
ExecNonQuery - Executes a "writing" statement and doesn't return any result. This can be for example: INSERT, UPDATE or CREATE TABLE.

ExecQuery - Executes a query statement and returns a Cursor object that is used to process the results.

ExecQuerySingleResult - Executes a query statement and returns the value of the first column in the first row in the result set. This method is a shorthand for using ExecQuery and reading the value with a Cursor.

We will analyze the example code:
Code:
Sub CreateTables
    SQL1.ExecNonQuery(
"DROP TABLE IF EXISTS table1")
    SQL1.ExecNonQuery(
"DROP TABLE IF EXISTS table2")
    SQL1.ExecNonQuery(
"CREATE TABLE table1 (col1 TEXT , col2 INTEGER, col3 INTEGER)")
    SQL1.ExecNonQuery(
"CREATE TABLE table2 (name TEXT, image BLOB)"
End Sub
The above code first deletes the two tables if they exist and then creates them again.

Code:
Sub FillSimpleData
    SQL1.ExecNonQuery(
"INSERT INTO table1 VALUES('abc', 1, 2)")
    SQL1.ExecNonQuery2(
"INSERT INTO table1 VALUES(?, ?, ?)"Array As Object("def"34))
End Sub
In this code we are adding two rows. SQL.ExecNonQuery2 receives two parameters. The first parameter is the statement which includes question marks. The question marks are then replaced with values from the second List parameter. The List can hold numbers, strings or arrays of bytes (blobs).
Arrays are implicitly converted to lists so instead of creating a list we are using the Array keyword to create an array of objects.

Code:
Sub LogTable1
    
Dim Cursor1 As Cursor
    Cursor1 = SQL1.ExecQuery(
"SELECT col1, col2, col3 FROM table1")
    
For i = 0 To Cursor1.RowCount - 1
        Cursor1.Position = i
        
Log("************************")
        
Log(Cursor1.GetString("col1"))
        
Log(Cursor1.GetInt("col2"))
        
Log(Cursor1.GetInt("col3"))
    
Next
    Cursor1.Close
End Sub
This code uses a Cursor to log the two rows that were previously added.
SQL.ExecQuery returns a Cursor object.
Then we are using the For loop to iterate over all the results.
Note that before reading values from the Cursor we are first setting its position (the current row).

Code:
Sub InsertManyRows
    SQL1.BeginTransaction
    
Try
        
For i = 1 To 500
            SQL1.ExecNonQuery2(
"INSERT INTO table1 VALUES ('def', ?, ?)"Array As Object(i, i))
        
Next
        SQL1.TransactionSuccessful
    
Catch
        
Log(LastException.Message)
    
End Try
    SQL1.EndTransaction
End Sub
This code is an example of adding many rows. Internally a lock is acquired each time a "writing" operation is done.
By explicitly creating a transaction the lock is acquired once.
The above code took less than half a second to run on a real device.
Without the BeginTransaction / EndTransaction block it took about 70 seconds.
A transaction block can also be used to guarantee that a set of changes were successfully done. Either all changes are made or none are made.
By calling SQL.TransactionSuccessful we are marking this transaction as a successful transaction. If you omit this line, all the 500 INSERTS will be ignored.
It is very important to call EndTransaction eventually.
Therefore the transaction block should usually look like:
Code:
SQL1.BeginTransaction
Try
  
'Execute the sql statements.
 SQL.TransactionSuccessful
Catch
 
'the transaction will be cancelled
 End Try
 
SQL.EndTransaction
Note that using transactions is only relevant when doing "writing" operations.

Blobs
The last two methods write an image file to the database and then read it and set it as the activity background.
Code:
Sub InsertBlob
    
'convert the image file to a bytes array
    Dim InputStream1 As InputStream
    InputStream1 = 
File.OpenInput(File.DirAssets, "smiley.gif")
    
Dim OutputStream1 As OutputStream
    OutputStream1.InitializeToBytesArray(
1000)
    
File.Copy2(InputStream1, OutputStream1)
    
Dim Buffer() As Byte 'declares an empty array
    Buffer = OutputStream1.ToBytesArray
    
    
'write the image to the database
    SQL1.ExecNonQuery2("INSERT INTO table2 VALUES('smiley', ?)"Array As Object(Buffer))
End Sub
Here we are using a special type of OutputStream which writes to a dynamic bytes array.
File.Copy2 copies all available data from the input stream into the output stream.
Then the bytes array is written to the database.

Code:
Sub ReadBlob
    
Dim Cursor1 As Cursor
    
'Using ExecQuery2 is safer as it escapes special characters automatically.
    'In this case it doesn't really matter.
    Cursor1 = SQL1.ExecQuery2("SELECT image FROM table2 WHERE name = ?"Array As String("smiley"))
    Cursor1.Position = 
0
    
Dim Buffer() As Byte 'declare an empty byte array
    Buffer = Cursor1.GetBlob("image")
    
Dim InputStream1 As InputStream
    InputStream1.InitializeFromBytesArray(Buffer, 
0, Buffer.Length)
    
    
Dim Bitmap1 As Bitmap
    Bitmap1.Initialize2(InputStream1)
    InputStream1.Close
    Activity.SetBackgroundImage(Bitmap1)
End Sub
Using a Cursor.GetBlob we fetch the previously stored image.
Now we are using an input stream that reads from this array and load the image.
Attached Files
File Type: zip SQL.zip (8.1 KB, 1179 views)
Reply With Quote
  #2 (permalink)  
Old 01-10-2011, 12:32 PM
nfordbscndrd's Avatar
Basic4ppc Expert
 
Join Date: Jan 2011
Location: Hot Springs Village, AR, USA
Posts: 792
Default Indexes

I have written a data-intensive program in VB6 using databases/tables created in Access2007. The database has over a half-dozen tables totalling over a gig.

The Archos 70 has a 250GB hard drive, so storing the databases should not be a problem, but each table has multiple indexes, most of them indexing 2+ fields combined. I have looked at the links you gave for SQLite, but cannot figure out if it offers the same ability of indexing multiple fields.

Also, it was not clear to me if an index can be created and stored in advance of running the app, or if it is created each time the app is run, which seems like it would really be time consuming with such large files. I'm also concerned about running such an app with the A70 only having 256MB of memory.

I downloaded a user's app (from the B4a site) which uses SQLite, but the demo version will not run it, so I can't experiment with SQLite. I don't have high hopes for getting my app onto the Archos 70, but this is my only need for Basic4android, so I wouldn't buy it without knowing if this will work.
Reply With Quote
  #3 (permalink)  
Old 01-10-2011, 03:00 PM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 15,689
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

SQLite supports multiple columns in the index. See the CREATE INDEX command: SQLite Query Language: CREATE INDEX
The index is stored in the database file. There is no need to recreate it each time.

I cannot estimate the performance of such a database on your device.
Reply With Quote
  #4 (permalink)  
Old 01-23-2011, 01:33 PM
nfordbscndrd's Avatar
Basic4ppc Expert
 
Join Date: Jan 2011
Location: Hot Springs Village, AR, USA
Posts: 792
Default

I am trying to run the following:

Cursor = SQL1.ExecQuery("SELECT * FROM Words")

I compile the app to a device, enter some text, click a button to execute this code, and get this error:

android.database.sqlite.SQLiteException: no such table: Words: , while compiling:
SELECT * FROM Words

I did an If File.Exists... to make sure the database is really there. The only table in the db is "Words".

If it helps, here is the Log:
Reply With Quote
  #5 (permalink)  
Old 01-23-2011, 03:10 PM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 15,689
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

Are you sure that the Words table exists in the database?
Can you upload the database (in a new thread preferably)?
Reply With Quote
  #6 (permalink)  
Old 01-23-2011, 03:47 PM
nfordbscndrd's Avatar
Basic4ppc Expert
 
Join Date: Jan 2011
Location: Hot Springs Village, AR, USA
Posts: 792
Default

Quote:
Originally Posted by Erel View Post
Are you sure that the Words table exists in the database?
Can you upload the database (in a new thread preferably)?
Yeah. Like I said, Words is the *only* table in the database.
It's at http://www.hsv-life.com/AIC/wordsdb.zip

I created it with SQLite DB Browser. You can see the Words table in this screen shot:
Reply With Quote
  #7 (permalink)  
Old 01-23-2011, 05:49 PM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 15,689
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

You can issue the following query to list all the tables:
Code:
SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;
Reply With Quote
  #8 (permalink)  
Old 01-23-2011, 06:08 PM
nfordbscndrd's Avatar
Basic4ppc Expert
 
Join Date: Jan 2011
Location: Hot Springs Village, AR, USA
Posts: 792
Default

Quote:
Originally Posted by Erel View Post
You can issue the following query to list all the tables:
Code:
SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;
When I insert that code and compile, I get an error message saying that "End Select" is missing.
Also, where does this display the table names? Do I have to add some code to do that?

Last edited by nfordbscndrd : 01-23-2011 at 06:10 PM.
Reply With Quote
  #9 (permalink)  
Old 01-23-2011, 08:38 PM
nfordbscndrd's Avatar
Basic4ppc Expert
 
Join Date: Jan 2011
Location: Hot Springs Village, AR, USA
Posts: 792
Default

After staring at this a dozen times, it dawned on me that the code you gave me needs to be in a Query, so I put in:

Code:
Cursor = SQL1.ExecQuery("Select name from sqlite_master _
               WHERE  Type='table' ORDER BY name;")
Cursor.Position = 0
Msgbox(Cursor.GetString("name"), "table:")
I got the response of "android_metadata".
Ooo-kay...
Reply With Quote
  #10 (permalink)  
Old 01-23-2011, 09:22 PM
nfordbscndrd's Avatar
Basic4ppc Expert
 
Join Date: Jan 2011
Location: Hot Springs Village, AR, USA
Posts: 792
Default

Success!

I Googled for "android_metadata" and found
Using your own SQLite database in Android applications | ReignDesign Blog

Followed the directions there and my Words table is now showing up.

Time for me to find a fresh piece of wall for me to bang my head against...
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are On

Similar Threads
Thread Thread Starter Forum Replies Last Post
GPS tutorial Erel Basic4android Getting started & Tutorials 62 05-22-2012 02:04 PM
SQL Tutorial Erel Tutorials 32 02-07-2011 09:14 AM
Need SQL tutorial Cableguy Basic4android Updates and Questions 11 11-30-2010 07:03 AM
Modules tutorial Erel Tutorials 3 07-05-2009 05:52 PM
New GPS tutorial Erel Announcements 2 11-05-2007 11:39 AM


All times are GMT. The time now is 10:22 AM.


Powered by vBulletin® Version 3.6.12
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0