Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

SQLite

SQLite is an open-source, serverless database engine designed for mobile and embedded applications, allowing for cross-platform data storage in a single file. It supports ACID transactions and requires minimal configuration, making it lightweight and efficient for devices with limited resources. The document also includes code examples for creating, connecting, and manipulating a SQLite database in an Android application.

Uploaded by

sonetshaji2004
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

SQLite

SQLite is an open-source, serverless database engine designed for mobile and embedded applications, allowing for cross-platform data storage in a single file. It supports ACID transactions and requires minimal configuration, making it lightweight and efficient for devices with limited resources. The document also includes code examples for creating, connecting, and manipulating a SQLite database in an Android application.

Uploaded by

sonetshaji2004
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

SQLite

It is an open-source database engine which implements a self-contained, serverless, zer


configuration, transactions

It stores potent data storage to mobile and embedded applications without a track

It can read and write to general disk files openly in which a single disk file contains multiple tables,
indices, triggers, and views

The database file layout is cross-platform – that is, it can copy a database between 32 and 64 bit file
systems or between big endian and little endian architectures

The code of SQLite is open to use for any purpose, private or public.

It is a compressed library in which the features are enabled. The size of the library can be reduced
below 300KiB. It could be run in minimal stack space and heap thus making it popular to be used in
gadgets such as mobile phones, PDAs and MP3 players. The performance of SQLite is relatively good
in low memory level requirements.

Why SQLite?

Serverless: It is serverless which does not need a detach server process or system to operate.

Zero configurations: It does not require any setup or administration.

Cross-platform: A compete SQLite database is stored in a single cross-platform disk file

Less memory: It is very small and light weight, less than 400 KiB completely configured or less than
250 KiB with optional features omitted.

Self-contained: It has no external dependencies

Transaction: SQLite transactions support ACID properties to allow safe access from multiple
processes or threads.

Languages and OS: It supports most of the query language features found in the SQL 92 (SQL2)
standard. It is written in ANSI C and provides simple and easy to use API. SQLite is accessible on UNIX
and Windows.

Creation and connection of the database

1. The package imported into the application is android.database.sqlite.SQLiteDatabase.


2. Here the class used is SQLiteDatabase.
3. The method used to create the database or connect to the database is
OpenOrCreateDatabase() method.

Program
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_blue_dark">

<TextView
android:text="@string/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="12dp"
android:id="@+id/textView"
android:textSize="18sp"
android:textStyle="bold|italic"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:gravity="center" />

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editName"
android:textStyle="bold|italic"
android:layout_below="@+id/textView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Enter Name"
android:gravity="center_vertical|center" />

<TextView
android:text="@string/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="13dp"
android:id="@+id/textView2"
android:textStyle="bold|italic"
android:textSize="18sp"
android:layout_below="@+id/editName"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:gravity="center"
android:hint="Enter Password" />

<Button
android:text="@string/view_data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:textSize="18sp"
android:onClick="viewdata"
android:textStyle="bold|italic"
android:layout_alignBaseline="@+id/button"
android:layout_alignBottom="@+id/button"
android:layout_alignRight="@+id/button4"
android:layout_alignEnd="@+id/button4" />

<Button
android:text="@string/add_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:textStyle="bold|italic"
android:textSize="18sp"
android:onClick="addUser"
android:layout_marginLeft="28dp"
android:layout_marginStart="28dp"
android:layout_below="@+id/editPass"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="23dp" />

<Button
android:text="@string/update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button3"
android:onClick="update"
android:textStyle="normal|bold"
android:layout_below="@+id/editText3"
android:layout_alignLeft="@+id/button4"
android:layout_alignStart="@+id/button4"
android:layout_marginTop="13dp" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editText6"
android:layout_alignTop="@+id/button4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:freezesText="false"
android:hint="Enter Name to Delete Data"
android:layout_toLeftOf="@+id/button2"
android:layout_toStartOf="@+id/button2" />

<Button
android:text="@string/delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="21dp"
android:layout_marginEnd="21dp"
android:id="@+id/button4"
android:onClick="delete"
android:textStyle="normal|bold"
tools:ignore="RelativeOverlap"
android:layout_marginBottom="41dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_marginTop="47dp"
android:id="@+id/editText3"
android:textStyle="bold|italic"
android:textSize="14sp"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="7dp"
android:layout_marginStart="7dp"
android:hint="Current Name" />

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:layout_marginTop="11dp"
android:id="@+id/editPass"
android:hint="Enter Password"
android:gravity="center_vertical|center"
android:textSize="18sp"
android:layout_below="@+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textAllCaps="false"
android:textStyle="normal|bold" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editText5"
android:textStyle="bold|italic"
android:textSize="14sp"
android:hint="New Name"
android:layout_alignTop="@+id/button3"
android:layout_alignLeft="@+id/editText3"
android:layout_alignStart="@+id/editText3"
android:layout_marginTop="32dp" />
</RelativeLayout>

package com.example.mydb;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


EditText Name, Pass , updateold, updatenew, delete;
myDbAdapter helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name= (EditText) findViewById(R.id.editName);
Pass= (EditText) findViewById(R.id.editPass);
updateold= (EditText) findViewById(R.id.editText3);
updatenew= (EditText) findViewById(R.id.editText5);
delete = (EditText) findViewById(R.id.editText6);

helper = new myDbAdapter(this);


}
public void addUser(View view)
{
String t1 = Name.getText().toString();
String t2 = Pass.getText().toString();
if(t1.isEmpty() || t2.isEmpty())
{
Toast.makeText(getApplicationContext(), "Enter Both Name and
Password", Toast.LENGTH_LONG).show();
}
else
{
long id = helper.insertData(t1,t2);
if(id<=0)
{
;
Name.setText("");
Pass.setText("");
} else
{
Toast.makeText(getApplicationContext(), "Insertion
Successful", Toast.LENGTH_LONG).show();
Name.setText("");
Pass.setText("");
}
}
}

public void viewdata(View view)


{
String data = helper.getData();

Toast.makeText(getApplicationContext(), data,
Toast.LENGTH_LONG).show();
}

public void update( View view)


{
String u1 = updateold.getText().toString();
String u2 = updatenew.getText().toString();
if(u1.isEmpty() || u2.isEmpty())
{

Toast.makeText(getApplicationContext(), "Enter Data",


Toast.LENGTH_LONG).show();
}
else
{
int a= helper.updateName( u1, u2);
if(a<=0)
{

Toast.makeText(getApplicationContext(), "Unsuccessful",
Toast.LENGTH_LONG).show();
updateold.setText("");
updatenew.setText("");
} else {

Toast.makeText(getApplicationContext(), "Updated",
Toast.LENGTH_LONG).show();
updateold.setText("");
updatenew.setText("");
}
}
}
public void delete( View view)
{
String uname = delete.getText().toString();
if(uname.isEmpty())
{

Toast.makeText(getApplicationContext(), "Enter Data",


Toast.LENGTH_LONG).show();
}
else{
int a= helper.delete(uname);
if(a<=0)
{

Toast.makeText(getApplicationContext(), "Unsuccessful",
Toast.LENGTH_LONG).show();
delete.setText("");
}
else
{

Toast.makeText(getApplicationContext(), "Deleted",
Toast.LENGTH_LONG).show();
delete.setText("");
}
}
}
}

package com.example.mydb;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Message;
import android.widget.Toast;

public class myDbAdapter {


myDbHelper myhelper;
public myDbAdapter(Context context)
{
myhelper = new myDbHelper(context);
}

public long insertData(String name, String pass)


{
SQLiteDatabase dbb = myhelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(myDbHelper.NAME, name);
contentValues.put(myDbHelper.MyPASSWORD, pass);
long id = dbb.insert(myDbHelper.TABLE_NAME, null , contentValues);
return id;
}

public String getData()


{
SQLiteDatabase db = myhelper.getWritableDatabase();
String[] columns =
{myDbHelper.UID,myDbHelper.NAME,myDbHelper.MyPASSWORD};
Cursor cursor
=db.query(myDbHelper.TABLE_NAME,columns,null,null,null,null,null);
StringBuffer buffer= new StringBuffer();
while (cursor.moveToNext())
{
@SuppressLint("Range") int cid
=cursor.getInt(cursor.getColumnIndex(myDbHelper.UID));
@SuppressLint("Range") String name
=cursor.getString(cursor.getColumnIndex(myDbHelper.NAME));
@SuppressLint("Range") String password
=cursor.getString(cursor.getColumnIndex(myDbHelper.MyPASSWORD));
buffer.append(cid+ " " + name + " " + password +" \n");
}
return buffer.toString();
}

public int delete(String uname)


{
SQLiteDatabase db = myhelper.getWritableDatabase();
String[] whereArgs ={uname};

int count =db.delete(myDbHelper.TABLE_NAME ,myDbHelper.NAME+"


= ?",whereArgs);
return count;
}

public int updateName(String oldName , String newName)


{
SQLiteDatabase db = myhelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(myDbHelper.NAME,newName);
String[] whereArgs= {oldName};
int count =db.update(myDbHelper.TABLE_NAME,contentValues,
myDbHelper.NAME+" = ?",whereArgs );
return count;
}

static class myDbHelper extends SQLiteOpenHelper


{
private static final String DATABASE_NAME = "myDatabase"; //
Database Name
private static final String TABLE_NAME = "myTable"; // Table Name
private static final int DATABASE_Version = 1; // Database
Version
private static final String UID="_id"; // Column I (Primary
Key)
private static final String NAME = "Name"; //Column II
private static final String MyPASSWORD= "Password"; // Column
III
private static final String CREATE_TABLE = "CREATE TABLE
"+TABLE_NAME+
" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+"
VARCHAR(255) ,"+ MyPASSWORD+" VARCHAR(225));";
private static final String DROP_TABLE ="DROP TABLE IF EXISTS
"+TABLE_NAME;
private Context context;

public myDbHelper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_Version);
this.context=context;
}

public void onCreate(SQLiteDatabase db) {

try {
db.execSQL(CREATE_TABLE);
} catch (Exception e) {

Toast.makeText(context.getApplicationContext(),
(CharSequence) e,Toast.LENGTH_LONG).show();
}
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
try {

Toast.makeText(context.getApplicationContext(),
"OnUpgrade",Toast.LENGTH_LONG).show();
db.execSQL(DROP_TABLE);
onCreate(db);
}catch (Exception e) {

Toast.makeText(context.getApplicationContext(),
(CharSequence) e,Toast.LENGTH_LONG).show();
}
}
}
}

Description

Import the package android.database.sqlite.SqLiteDatabase to the new android project.

An SQLiteDatabase variable is initialized with the database instance.

OpenOrCreateDatabase() method is used to open the database.

This method needs the database files first, followed by the permissions to open the database with
an optional cursor factory builder.

Android stores SQLite databases in data/data/[project package name]/databases.

Properties to setting the database

There are some database properties that must be set after connecting to the database. They are;

1. setVersion(): It sets the database version.


2. setLocale(): It sets the default locale from the database.
3. setLockingEnabled(): It enables locking on the database.

How can we create tables

1. After executing the statements, the table is created on the database.


2. The queries are executed by the execSQL() statement.
3. After opening the database, we configure the database connection with setVersion() to set
the database version.
4. The setLocale() method sets the default locale for the database and setLockingEnabled()
enables locking on the database.
5. Then we set up final string variables to hold the SQLite table creation statements and
execute them with execSQL().
6. We should create triggers to handle the foreign key relationships between the tables.
7. In the application, there also require foreign key triggers to handle row updates and deletes
the foreign key triggers are executed with execSQL() just like the table creation.

How can we insert the records?

1. Android contains a series of classes that make simpler database handling.


2. We use a contentvalues instance to create a series of table field to data matchings that will
be passed into an insert() method.
3. Android has created alike methods for updating and deleting records.
4. First we create a contentvalues object to store the data to insert and use the put() method
to load the data.
5. Then we use the insert() method to insert records into SQLite. The insert() method contains
3 parameters;
1. Table name
2. Null
3. ContentValues pairs
6. The insert() function returns long which hold the primary key of the inserted row
7. Then we create a new ContentValues pair for the state and execute a second insert() using
the insertOrThrow() method.
8. Using insertOrThrow() will throw an exception if the insert isn’t successful and should be
enclosed by the try/catch block.
9. We observe that presently the application terminates with an unhandled exception because
the tables we are trying to create previously exist.
10. Then we need to go back and drop the tables.

How can we update the data in the database

1. The update() method is used to update records in the database


2. The update() function supports where syntax like other SQL engines. The update() method
contains the parameters;
1. Table name
2. ContentValues instance
3. Optional where syntax
4. Usage of ?

How can we delete records from the database

1. If data is no longer required in the database, then we use the delete option to delete records
from the database
2. The delete() method expects 3 parameters;
 Database name
 Where clause
 An argument array for the where clause
3. To delete all the records from the table, pass null for the where clause and where clause
argument array
4. Only we call the delete() method to remove records from SQLite database
5. The delete method contains the table name and optionally the where clause and anywhere
clause argument replacement arrays as parameters
6. The where clause and argument replacement array work just as with update where ? is
replaced by the values in the array

How can we retrieve the data from the database

1. Retrieving data from SQLite databases is done using cursors


2. The android SQLite query method returns a cursor object containing the results of the query
3. The package used for Cursors is android.database.cursor

Extracting values from cursor

Cursors stores query result records in rows and grant many methods to access and iterate through
records

Cursors should be closed when no longer used and can be deactivated with a call to
Cursor.deactivate() statement when the application pauses or exits

On resume, the Cursor.requery() statement is executed to re enable the cursor with fresh data.

Transactions

When we want to execute a series of queries that either all complete or all fail, at that situation we
use transactions which is supported by SQLite

When an SQLite transaction fails, an exception will be thrown.

There are 3 methods available in transaction;

1. beginTransaction()
2. setTransactionSuccessful()
3. endTransaction()

Program
 Start with a call to beginTransaction () to inform SQLite to execute the queries in transaction
mode.
 Begin a try/catch mode to handle exceptions thrown by a transaction failure.
 Perform the queries and then call setTransactionSuccessful() to inform SQLite that our
transaction is complete.
 If an error isn’t thrown, then endTransaction() can be called to perform the transaction.
Finally, close the cursor when we are finished.

You might also like