Detailed usage of SQLite

Posted by lillyapps on Tue, 06 Aug 2019 11:27:59 +0200

Strongly Recommend Articles: Welcome to Collection
Android Dry Goods Sharing

Read for five minutes, ten o'clock a day, and study with you for life. Here's Android, a programmer.

This article mainly introduces some knowledge points in Android development. By reading this article, you will gain the following contents:

  1. Inheriting SQLiteOpenHelper to create databases and tables
  2. Insert database data
  3. Delete database data
  4. Query database data
  5. Modify database data
  6. Use case of database

Android provides a pair of SQLite Full support of the database. Any class in the application (excluding those outside the application) can access any database you create by name. If you want the database you create to be used by external applications, use ContentProvider to provide an interface. The use of SQLite lightweight database is as follows:

1. Inheriting SQLiteOpenHelper to create databases and tables

Create database tables

1. Grammar

The syntax for creating data tables is as follows:

2. Examples

Examples are as follows:

3. Inheriting SQLiteDBHelper to create databases and tables

The methods of creating database and data table are as follows:

4. Delete database tables

The method of deleting database tables is as follows:

DROP TABLE IF EXITS TABLE_NAME;

2. Insert database data

Method 1 for inserting data

  1. grammar

INSERT INTO TABLE_NAME [(column1, column2, column3,...columnN)]  
VALUES (value1, value2, value3,...valueN);

  1. Give an example

INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Paul', 32, 'California', 20000.00 );

Data insertion method 2

  1. grammar

INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

  1. Give an example

INSERT INTO COMPANY VALUES (7, 'James', 24, 'Houston', 10000.00 );

Android encapsulation insert() insert data method 3

1. Grammar

insert(String table, String nullColumnHack, ContentValues values)

2. Examples

private SQLiteDatabase db;
db.insert(SQLiteDBHelper.TABLE_NAME, null, values);

3. Delete database data

Method 1 for deleting database data

1. Grammar

DELETE FROM table_name 
WHERE [condition];

2. Examples

DELETE FROM COMPANY WHERE ID = 7;

2.Android encapsulation and deletion of database data method 2

1. Grammar

delete(String table, String whereClause, String[] whereArgs)

Give an example

private SQLiteDatabase db;
db.delete(SQLiteDBHelper.TABLE_NAME, "name=?",
                new String[] { "Jack" });

4. Query database data

Query database method 1

1. Grammar

SELECT column1, column2, columnN FROM table_name;

Method of querying all data in a table

SELECT * FROM table_name;

2. Examples

//1. Query the specified column
SELECT ID, NAME, SALARY FROM COMPANY;
// 2. All contents in the query table
SELECT * FROM COMPANY;

Android encapsulation query database method 2

1. Grammar

query(String table, String[] columns, String selection,
            String[] selectionArgs, String groupBy, String having,
            String orderBy)

2. Examples

private SQLiteDatabase db;
Cursor cursor = db.query(SQLiteDBHelper.TABLE_NAME, null, null, null,
                null, null, null);

5. Modify database data

Modifying database method 1

1. Grammar

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

2. Examples

UPDATE COMPANY SET ADDRESS = 'Texas' WHERE ID = 6;

Android update encapsulation and modification of database method 2

1. Grammar

update(String table, ContentValues values, String whereClause, String[] whereArgs)

2. Examples

db.update(SQLiteDBHelper.TABLE_NAME, values, "nickname=?",
                new String[] { "J" });

6. Case study of database usage

  • Achieving results

Create a database

The method of creating database is as follows:

public class SQLiteDBHelper extends SQLiteOpenHelper {
    public static String DB_NAME = "person.db";
    // version must be greater than 1
    public static int DB_VERSION = 1;
    public static String TABLE_NAME = "person";
    public static String _ID = "_id";
    public static String NAME = "name";
    public static String NICK_NAME = "nickname";

    public SQLiteDBHelper(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub
    }

    public SQLiteDBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        // In SQLite databases, fields are typeless, except for primary keys, which must be integer.
        String sql = "CREATE TABLE " + TABLE_NAME + "(" + _ID
                + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL" + "," + NAME
                + " CHAR(10)," + NICK_NAME + " CHAR(10))";
        db.execSQL(sql);
    }

    // Processing method of database upgrade,
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        if (newVersion > oldVersion) {
            // Delete old tables and create new ones
            String dropsql = "DROP TABLE IF EXITS " + TABLE_NAME;
            db.execSQL(dropsql);
            onCreate(db);
        }
    }

}

Implementing the Method of Adding Data to Database

The implementation code of the method of adding data to the database is as follows:

    //
    public void InsertSQL(View view) {

        InstertDB();
        QueryDB();
    }

    /**
     * Insertion Data Processing Method
     */
    private void InstertDB() {
        ContentValues values = new ContentValues();
        values.put("name", "Jack");
        values.put("nickname", "J");

        // Return value: the line number of the most recently inserted line
        long result = db.insert(SQLiteDBHelper.TABLE_NAME, null, values);
        if (result > 0) {
            Toast.makeText(getApplicationContext(), "Added Successfully", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Toast.makeText(getApplicationContext(), "Failure to add", Toast.LENGTH_SHORT)
                    .show();
        }
    }

Implementation of Content Deletion Method in Database

The implementation code of the database deletion method is as follows:

    /**
     * Delete data
     */
    private void DeleteDb() {
        int result = db.delete(SQLiteDBHelper.TABLE_NAME, "name=?",
                new String[] { "Jack" });
        if (result > 0) {
            Toast.makeText(getApplicationContext(), "Successful deletion", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Toast.makeText(getApplicationContext(), "nothing Jack", Toast.LENGTH_SHORT)
                    .show();
        }
    }

Implementation of Content Modification Method in Database

The implementation code of database modification content method is as follows:

    /**
     * Modify data
     */
    private void UpdateDb() {
        // update person set name="Kitty" where nickname="J"
        ContentValues values = new ContentValues();
        values.put("name", "Lucy");

        int result = db.update(SQLiteDBHelper.TABLE_NAME, values, "nickname=?",
                new String[] { "J" });

        if (result > 0) {
            QueryDB();
        }
    }

Implementation of database query method

The implementation code of the database query method is as follows:

    /**
     * Query Data Processing Method
     */
    private void QueryDB() {
        // Select * from person where name= ?
        // db.rawQuery(s)
        // Cursor cursor - "result set"
        // When using SimpleCusorAdapter, cursor must contain "_id" in the record.
        // Cursor cursor = db.query(SQLiteDBHelper.TABLE_NAME, null, "name=?",
        // new String[] { "Jack" }, null, null, null);
        Cursor cursor = db.query(SQLiteDBHelper.TABLE_NAME, null, null, null,
                null, null, null);

        while (cursor.moveToNext()) {

            String name = cursor.getString(cursor.getColumnIndex("name"));
            String nickname = cursor.getString(cursor
                    .getColumnIndex("nickname"));
        }
        // Exchange a new cusor with the original customer
        adapter.swapCursor(cursor);
        adapter.notifyDataSetChanged();
    }
  • The layout is as follows
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/insertdata"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="InsertSQL"
        android:text="Adding data" />
    <Button
        android:id="@+id/deletedata"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="DeleteSQL"
        android:text="Delete data" />
    <Button
        android:id="@+id/quarydata"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="QuarySQL"
        android:text="Query data" />
    <Button
        android:id="@+id/modifydata"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="ModifySQL"
        android:text="Modify data" />
    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
  • The ListView item layout is as follows
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:padding="10dp" >

    <TextView
        android:id="@+id/name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="name" />

    <TextView
        android:id="@+id/nickname"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="nickname" />

</LinearLayout>

So far, this article is over. If there are any mistakes, you are welcome to make suggestions and corrections. At the same time look forward to your attention, thank you for reading, thank you!

Topics: Android Database SQLite SQL