Sql queries - Basics

8

Click here to load reader

Transcript of Sql queries - Basics

Page 1: Sql queries - Basics

SQL QUERIES

Purvik Rana

Page 2: Sql queries - Basics

Let you perform Database related operations (CRUD Operations)

Operations like:

• Create – to create require specific tables in database

• Insert –to write your data to the tables

• Update – to update/modify data that you have written in tables of database

• Delete – to remove/delete data from the tables and or whole table/database

Page 3: Sql queries - Basics

create Create table statement

CREATE TABLE table_name ( column1 datatype, column2 datatype, column3 datatype, ..... columnN datatype, PRIMARY KEY ( one or more columns ) );

Example:

CREATE TABLE " + TABLE_STUDENT_DETAIL + “ ( "

+ KEY_ID + " INTEGER PRIMARY KEY,"

+ KEY_ENROLL_NO + " TEXT,"

+ KEY_NAME + " TEXT,"

+ KEY_PHONE_NO + " TEXT " + ")";

CREATE TABLE studentDetails ( id INTEGER PRIMARY KEY, enroll_no TEXT, name TEXT, phone_number TEXT);

To execute :

SQLiteDatabase.execSQL(your_query);

id enroll_no name phone_number

Page 4: Sql queries - Basics

read To read specific or all data from tables

SELECT * FROM table_name; // syntax “ SELECT * FROM ” + TABLE_STUDENT_DETAIL; // example

Cursor - Is a control structure that enables traversal over the records in a database Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { Student stdnt = new Student(); stdnt.set_id ( Integer.parseInt ( cursor.getString(0) ) ); stdnt.set_enroll_no ( Integer.parseInt ( cursor.getString(1) ) ); stdnt.set_name ( cursor.getString(2) ); stdnt.set_phone_number ( cursor.getString(3) ); // display/process on the retrived values

} while ( cursor.moveToNext() ); }

Page 5: Sql queries - Basics

update Syntax

UPDATE table_name SET column1 = value1, column2 = value2....columnN = valueN [ WHERE CONDITION ];

Example

UPDATE studentDetails SET id = 1, enroll_no = “1001”, name = “NAME”, phone_number = “6548465”;

Programming

ContentValues args = new ContentValues();

args.put ( KEY_ENROLL_NO, updEnrolNo );

args.put ( KEY_NAME, updName );

args.put ( KEY_PHONE_NO, updPhoneNo );

SQLiteDatabase.update ( TABLE_STUDENT_DETAIL, args, KEY_ID + "=" + 1, null ) > 0;

Page 6: Sql queries - Basics

Delete Drop Table (Syntax)

DROP TABLE IF EXISTS table_name;

Example

DROP TABLE IF EXISTS studentDetails;

Drop Specific Row Data Syntax

DELETE FROM table_name WHERE {CONDITION}; //delete based on condition (syntax)

Example

SQLiteDatabase.delete ( TABLE_STUDENT_DETAIL, KEY_ID + "=" + 1, null ) > 0;

Page 7: Sql queries - Basics

CRUD HANDLES DB ACTIVITIES EFFECTIVELY

Stays apart from your code region

Handles all relative database operations

Encapsulated implementation in Programming

Page 8: Sql queries - Basics

BASIC OF DESIGNING NEXT SESSION