Lecture 13 File Handling and SQLite DBMS
Lecture 13 File Handling and SQLite DBMS
output.println("Hello, world!");
output.println("How are you?");
output.close();
...
// read the same file, and put its contents into a TextView
Scanner scan = new Scanner(
openFileInput("out.txt", MODE_PRIVATE));
String allText = ""; // read entire file
while (scan.hasNextLine()) {
String line = scan.nextLine();
allText += line;
}
myTextView.setText(allText);
scan.close();
Internal storage example 2
while (scan.hasNextLine()) {
String line = scan.nextLine();
allText += line;
}
myTextView.setText(allText);
scan.close();
Database Management using SQLite
What Is a DBMS?
A database is an organized collection of data.
● Oracle
● Microsoft
– SQL Server (powerful)
– Access (simple)
● PostgreSQL
– powerful/complex free open-source database system
● SQLite
– transportable, lightweight free open-source database system
● MySQL
– simple free open-source database system
– many servers run "LAMP" (Linux, Apache, MySQL, and PHP)
– Wikipedia is run on PHP and MySQL
Android SQLite
SQLite is an open-source relational database i.e. used to perform database
operations on android devices such as storing, manipulating or retrieving
persistent data from the database.
General Syntax:
SQLiteDatabase db = openOrCreateDatabase("name", MODE_PRIVATE, null);
db.execSQL("SQL query");
Example: Creating Object for Database
● NOT NULL: empty value not allowed in any row for that column
● PRIMARY KEY / UNIQUE: no two rows can have the same value
Example: Creating a Table
Example 1:
Note: If you have created a table once and try to create it again then
Android Studio will give an error
OR
db.execSQL("create table if not exists teacherTab(name varchar(20))");
Example 2:
Example 1:
Example 2:
int val1=10;
String val2="Mubeen";
Example:
db.rawQuery("select * from StudentTab", null);
int column=1; // it’s column number you want to extract from table
if (cursor.moveToFirst()) {
do {
String s =cursor.getString(column);
} while (cursor.moveToNext());
}
Example: Select statement using Cursor
Cursor cursor = db.rawQuery("select * from StudentTab", null);
String no="s_no";
String name_id="name";
String s1="";
if (cursor.moveToFirst()) {
do {
s1 = s1 +" "+
cursor.getString(cursor.getColumnIndex(no))+" “
+ cursor.getString(cursor.getColumnIndex(name_id));
} while (cursor.moveToNext());
}
tv1.setText(s1);
Example: Putting it all together (Create, Insert,
and Select Query Examples)
SQLiteDatabase db = openOrCreateDatabase("Teacher", MODE_PRIVATE, null);
//db.execSQL("create table StudentTab(s_no integer, name varchar(20))");
String no="s_no";
int val1=10;
String name_id="name";
String val2="Mubeen";
String s1="";
if (cursor.moveToFirst()) {
do {
s1 = s1 +" "+ cursor.getString(cursor.getColumnIndex(no))+" “
+ cursor.getString(cursor.getColumnIndex(name_id));
} while (cursor.moveToNext());
}
tv1.setText(s1);