Database Handling
Database Handling
(INNER) JOIN : Returns records that have matching values in both tables
LEFT (OUTER) JOIN : Returns all records from the left table, and the matched records from the right
table
RIGHT (OUTER) JOIN : Returns all records from the right table, and the matched records from the left
table
FULL (OUTER) JOIN : Returns all records when there is a match in either left or right table
1. Using Joins
[Link](currDate);
[Link](start);
}
catch (NullPointerException ne){ [Link](); }
catch (ArrayIndexOutOfBoundsExceptionae){ [Link](); }
catch (CursorIndexOutOfBoundsException ci) { [Link](); }
catch (Exception e){ [Link](); }
}
catch([Link])
{}
Database Transactions
You have to set begin transaction if you have multiple records to insert into database or if you have to rollback data from other
table if there is a problem in inserting data in one of the database table.
For example
1. A
2. B
Now you want to insert data in these two tables but you will have to rollback transaction if you will get any error at the time of
inserting data in the tables.
Now you have successfully insert data in table A and now you are trying to insert data in the table [Link] if you get error at the
time of inserting data in the table B then you have to delete relevant data from table A that means you have to rollback the
transaction.
1. If you want to set transaction successful you need to write setTransactionSuccessful() and then endTransaction()
after beginTransaction()
2. If you want to rollback your transaction then you need to endTransaction() without committing the transaction by
setTransactionSuccessful().
You can get detailed information about the SQLite database transaction from here
In your case
You can call your saveCustomer() function in try and catch blocks
[Link]();
try {
saveCustomer();
[Link]();
} catch {
//Error in between database transaction
} finally {
[Link]();
}
If there is an exception in the ... in your above code, the code you already have will automatically roll back the transaction. The
finally {} block is executed after the catch() {} block.
DROP TABLE IF EXISTS Products;
SELECT NAME FROM EMP WHERE NAME LIKE '%AM' OR NAME LIKE 'RA%'
--------------------------------------------------------------------------------------
OUTPUT :
ID NAME AGE ADDRESS SALARY
INT TEXT INT CHAR(50) REAL
----------------------------------------------------
1 ram 24 janakpuri 30000.0
2 kamal 30 madanpuri 3000.0
3 madan 27 kalyanpuri 45000.0
4 kabeer 20 palam 50000.0
5 ravi 14 cant 100000.0
6 mohan 33 laxi nagar 35000.0
OUTPUT :
========
NAME SALARY
TEXT REAL
-------------------------------------------------------------
kamal 3000.0
annu 8000.0
kavi 10000.0
dev 23000.0
ruchi 27000.0
ram 30000.0
mohan 35000.0
madan 45000.0
kabeer 50000.0
ravi 100000.0
-------------------------------------------------------------
SELECT * FROM EMP ORDER BY ADDRESS, SALARY ASC;
OUTPUT :
========
OUTPUT :
========
NAME SUM(SALARY)
TEXT float
-----------------------------------------------------------------
annu 8000.0
dev 23000.0
kabeer 50000.0
kamal 43000.0
madan 45000.0
mohan 35000.0
ravi 100000.0
ruchi 27000.0
-----------------------------------------------------------------
OUTPUT :
========
NAME SUM(SALARY)
TEXT float
-----------------------------------------------------------------
annu 8000.0
dev 23000.0
kabeer 50000.0
kamal 43000.0
madan 45000.0
mohan 35000.0
ravi 100000.0
ruchi 27000.0
-----------------------------------------------------------------
HAVING Clause
The HAVING clause enables you to specify conditions that filter which group results appear in the final results.
OUTPUT :
========
DISTINCT Keyword
The SQLite DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the duplicate records and fetching only unique records.
output :
========
NAME
TEXT
----------------------------------------------------
kamal
madan
kabeer
ravi
dev
ruchi
annu
----------------------------------------------------
CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL UNIQUE,
ADDRESS CHAR(50),
SALARY REAL DEFAULT 50000.00
RATE REAL CHECK(RATE > 0)
);
CROSS JOIN
INNER JOIN
SELECT [Link],[Link],[Link],dep.emp_id
FROM emp INNER JOIN dep
ON [Link] = dep.emp_id;
OUTPUT :
========
ID DEPT EMP_ID
INT TEXT INTEGER
-----------------------------------
1 BILLING 3
2 SALES 1
3 BILLING 2
4 BILLING 5
5 MARKETING 6
6 PRODUCTION 4
7 BILLING 7
8 PRODUCTION 9
9 PRODUCTION 8
10 PRODUCTION 10
-----------------------------------
SALARY
REAL
---------
3000.0
8000.0
10000.0
23000.0
27000.0
30000.0
35000.0
45000.0
50000.0
100000.0
---------
SELECT MAX(Salary) FROM EMP WHERE Salary NOT IN (SELECT MAX(Salary) FROM EMP );
MAX(Salary)
float
-------------
50000.0 (Second maximum salary)
-------------
SELECT MAX( SALARY ) FROM EMP WHERE SALARY < ( SELECT MAX( SALARY ) FROM EMP );
MAX( SALARY )
float
---------------
50000.0 (Second maximum salary)
---------------
SELECT MAX( SALARY ) FROM EMP WHERE SALARY < ( SELECT MAX( SALARY ) FROM EMP WHERE SALARY < ( SELECT
MAX( SALARY ) FROM EMP ));
MAX( SALARY )
float
---------------
45000.0 (Third maximum salary)
---------------
You can get n-th salary by arranging the table in desc order, then pick the n-th record.
How does one eliminate duplicates rows from a table using DELETE query?
MAX(id)
integer
--------------
10
8
4
2
7
3
6
5
9
--------------
DELETE FROM emp WHERE id NOT IN (SELECT MAX(id) FROM emp GROUP BY name);
INSERT INTO emp('id', 'name', 'salary') SELECT id, name, salary FROM employee
Following is an example where we will create an index in COMPANY table for salary column −
list down all the indices available in COMPANY table using .indicescommand as follows −
This will produce the following result, where sqlite_autoindex_COMPANY_1 is an implicit index which got created when the table
itself was created.
salary_index
sqlite_autoindex_COMPANY_1
Now selecting the data from table COMPANY you can use INDEXED BY clause as follows −
sqlite> SELECT * FROM COMPANY WHERE salary > 5000 INDEXED BY salary_index;
You can use the following statement to delete previously created index.
SQLite is an Open Source database comes as a build in database in Android OS. The APIs you'll need to use a database on Android are available in the
[Link] package.
// Empty constructor
public Contact(){}
// constructor
public Contact(int id, String name, String _phone_number)
{
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
// constructor
public Contact(String name, String _phone_number)
{
this._name = name;
this._phone_number = _phone_number;
}
// getting ID
public int getID()
{
return this._id;
}
// setting id
public void setID(int id)
{
this._id = id;
}
...
}
The data handler will be implemented by subclassing the SQLiteOpenHelper class and overriding the onCreate() and onUpgrade() methods. Since the databse handler
will be required to add, query and delete data on behalf of the activity component, corresponding methods will also need to be added to the class.
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
SQLiteDatabase db;
db = [Link]();
}
@Override
public void onCreate(SQLiteDatabase db)
{
[Link]("CREATE TABLE " + TABLE_NAME + "( id INTEGER PRIMARY KEY, name TEXT, phone_number TEXT )");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.d("MSNEGI","onUpgrade called");
[Link]("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
// Inserting Row
[Link](TABLE_NAME, null, values);
Log.d("MSNEGI","Record added...");
}
/*
* According to the docs
* [Link]
* /sqlite/[Link] Writers should use
* beginTransactionNonExclusive() or
* beginTransactionWithListenerNonExclusive(SQLiteTransactionListener)
* to start a transaction. Non-exclusive mode allows database file to be
* in readable by other threads executing queries.
*/
[Link]();
// [Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
[Link]();
return contact;
}
[Link]()
// updating row
[Link]();
return [Link](TABLE_NAME, values, _ID + " = ?", new String[]{ [Link]([Link]()) });
}
The onCreate() method needs to be implemented so that the database tables are created when the database is first created. This involves constructing a SQL CREATE
statement containing instructions to create a new table(s) with the appropriate columns and then passing that to the execSQL() method of the SQLiteDatabase object as
an argument to onCreate().
The onUpgrade() method is called when the handler is invoked with a greater database version number from the one previously used. The exact steps to be performed
in this instance will be application specific, so for the purposes of this example we will simply remove the old database and create a new one.
Then, other methods are required to add, read and delete records from the table(s).
Using DatabaseHelper
To access the database, create an instance of DatabaseHelper . Creating an instance of DatabaseHelper will create an instance of specified database and tables inside
the database if not already exist. Then, call the addContact() method to add records to the table.
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
[Link](new Contact("Ram", "9876543211"));
[Link](new Contact("Raj", "9734674433"));
[Link](new Contact("Amisha", "4356789032"));
[Link](new Contact("kapil", "3456789023"));
Another way -
contacts = [Link]();
//deleteContact
for (Contact cn : contacts)
{
if([Link]() == 18)
{
[Link](cn);
}
}
You may use another way to insert records which is several times faster then normal insert method.
[Link]("johan","1234567890");
contacts = [Link]();
dependencies {
compile '[Link]:appcompat-v7:26.+'
compile '[Link]:constraint-layout:1.0.2'
compile files('libs/[Link]')
}
activity_main.xml
<RelativeLayout xmlns:android="[Link]
android:id="@+id/activity_main_linear_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:padding="5dp"
android:layout_marginTop="20dp"
android:text="Choose city of departure:"
android:textSize="16sp" />
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView1"
android:layout_alignParentTop="true"
android:layout_toRightOf="@id/textView1"
/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@id/textView1"
android:padding="5dp"
android:text="The rally runs until December 13, 2014"
android:textSize="16sp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/relativelistlayout"
android:layout_below="@id/textView2" >
<ListView
android:id="@+id/trainListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:paddingTop="10dp" >
</ListView>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_below="@id/trainListView"
android:text="More information at [Link] />
</RelativeLayout>
</RelativeLayout>
Train_item_layout.xml
<RelativeLayout xmlns:android="[Link]
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/city_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:padding="5dp"
/>
<TextView
android:id="@+id/time_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
/>
</RelativeLayout>
[Link]
</resources>
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
db = new MyDatabase(getApplicationContext());
values = new ArrayList<TrainItem>();
adapter = new AdapterForTrainDepartures(this, values);
[Link]([Link].simple_dropdown_item_1line);
[Link](adapter);
[Link](spinnerAdapter);
[Link](this);
@Override
protected void onDestroy() {
[Link]();
[Link]();
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
switch (position) {
case 0:
[Link]();
[Link]([Link]());
[Link]();
break;
case 1:
[Link]();
[Link]([Link]());
[Link]();
break;
case 2:
[Link]();
[Link]([Link]());
[Link]();
break;
case 3:
[Link]();
[Link]([Link]());
[Link]();
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
[Link]
package [Link];
int id;
String destination;
String timeOfDeparture;
public TrainItem(){
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Override
public int getCount() {
return [Link]();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) [Link](Context.LAYOUT_INFLATER_SERVICE);
[Link]([Link]);
[Link]([Link]);
return view;
}
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
[Link](sqlTables);
Cursor cursor = [Link](db, sqlSelect, null, null, null, null, null);
if ([Link]()) {
while ([Link]() == false) {
TrainItem item = new TrainItem([Link]([Link](0)),
[Link](1), [Link](2));
[Link](item);
[Link]();
}
}
[Link]();
return values;
}
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
[Link](sqlTables);
Cursor cursor = [Link](db, sqlSelect, null, null, null, null, null);
if ([Link]()) {
while ([Link]() == false) {
TrainItem item = new TrainItem([Link]([Link](0)),
[Link](1), [Link](2));
[Link](item);
[Link]();
}
}
[Link]();
return values;
}
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
[Link](sqlTables);
Cursor cursor = [Link](db, sqlSelect, null, null, null, null, null);
if ([Link]()) {
while ([Link]() == false) {
TrainItem item = new TrainItem([Link]([Link](0)),
[Link](1), [Link](2));
[Link](item);
[Link]();
}
}
[Link]();
return values;
}
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
[Link](sqlTables);
Cursor cursor = [Link](db, sqlSelect, null, null, null, null, null);
if ([Link]()) {
while ([Link]() == false) {
TrainItem item = new TrainItem([Link]([Link](0)),
[Link](1), [Link](2));
[Link](item);
[Link]();
}
}
[Link]();
return values;
}
}