Detailed explanation of addition, deletion and modification of sqlite

Posted by markszy on Sat, 25 May 2019 01:39:01 +0200

Add, delete and modify the source code:

myHelper.java

package com.example.sqlite3lianxi;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class myHelper extends SQLiteOpenHelper {

    /*
     *  Parameters (context, database file name, factory cursor, database file version number)
     */
    public myHelper(Context context, String name, CursorFactory factory, int version) {
        super(context, "people.db", null,version);
    }

    //Called after successful creation of database file
    @Override
    public void onCreate(SQLiteDatabase db) {
        //SQLiteDatabase db is a database operation object
        //Note that this method will not be executed if there is a local database
        db.execSQL("create table people(id integer,name text)");
        System.out.println("Create success!");
    }

    //Called when database files need to be updated
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        System.out.println("The database update is complete!");
    }

}

MainActivity.java

package com.example.sqlite3lianxi;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Note that the execution of this sentence did not create the database, only created the object.
        myHelper helper=new myHelper(getBaseContext(),null, null, 2);
        //When this sentence is executed, the completed database is created.
        helper.getWritableDatabase();


    }
    //Add data
    public void insert() {
        //Creating database objects
        myHelper helper=new myHelper(getBaseContext(),null, null, 2);
        //Return database operation object
        SQLiteDatabase database=helper.getReadableDatabase();

        ContentValues values=new ContentValues();
        values.put("name","Lao Wang");
        values.put("name","Lou Reed");
        //Returns the id of an id data, and - 1 if insertion fails
        //Parameters (table name, null, insert value)
        long g=database.insert("people", null, values);

        //Close database connection
        database.close();
    }

        //Delete data
        public void delete() {
            //Creating database objects
            myHelper helper=new myHelper(getBaseContext(),null, null, 2);
            //Return database operation object
            SQLiteDatabase database=helper.getReadableDatabase();

            //Parameters (table name, deletion condition, value of deletion condition)
            //Returns the number of rows affected i
            int t=database.delete("people","name=?",new String[] {"Lao Liu"});

            //Close database connection
            database.close();
        }

              //Modifying data
                public void update() {
                    //Creating database objects
                    myHelper helper=new myHelper(getBaseContext(),null, null, 2);
                    //Return database operation object
                    SQLiteDatabase database=helper.getReadableDatabase();
                    ContentValues values=new ContentValues();
                    //Parameters (Table Name, Value to be Modified, Conditions to be Modified, Conditions to be Modified)
                    values.put("name","Xiaohong");
                    //Returns the number of rows affected i
                    //If you want to change all the tables, you can not specify conditions. update ("people", "null", null);
                    int t=database.update("people", values,"name=?",new String[] {"Lou Reed"});

                }
                //Query data
                public void query() {
                    //Creating database objects
                    myHelper helper=new myHelper(getBaseContext(),null, null, 2);
                    //Return database operation object
                    SQLiteDatabase database=helper.getReadableDatabase();
                    /*  Parameters:
                     *  distinct Whether to remove duplicate data
                     *  table Table name, column to be queried by columns
                     *  selection Screening Conditions Rules
                     *  selectionArgs Values of filter condition rules
                     *  grounBy Grouping
                     *  having Group selection
                     *  orderBy Sort//ascending or descending
                     *  limit paging
                     */
                    //Returns the result set of the query
                    Cursor cursor=database.query(true, "people", new String[] {"name"},null, null,null,null,null,null);
                    //Traversal result set
                    while(cursor.moveToNext()) {

                        String name=cursor.getString(cursor.getColumnIndex("name"));
                        System.out.println("name="+name);
                    }

                    //Close database connection
                    database.close();
                }
}

Summary of Addition, Deletation and Amendment:

To implement sqlite add, delete and modify queries, we need to write a class that inherits from the SQLiteOpenHelper class.
Two new methods and one construction method are proposed.

   //Parameters (context, database file name, factory cursor, database file version number)
    public myHelper(Context context, String name, CursorFactory factory, int version);

    //Called after successful creation of database file
     @Override
   public void onCreate(SQLiteDatabase db){};

    //Called when database files need to be updated
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){}

Let it be de-instantiated in the main MainActivity, which returns the database operation object, and uses this database operation object to realize database addition, deletion and modification.

You will find that using this encapsulated database operation object to achieve database addition, deletion and modification can also use some simple SQL statements, but the implementation of complex SQL statements is not enough, so we need to use the original statement of SQL, we use the method of returning database operation pixel execSQL(sql statement) to use complex SQL statements;

Example:
Add, delete and modify our use of:
execSQL(); Method

But add, delete and change the result set without returning. We can use the execSQL() method.
But if we want to query the result to return the result set, we can't use the execSQL() method, so we need to use the execSQL() method.

Example:
For queries, we use:
Db. rawQuery (sql statement of filter condition, value of filter condition);
It returns a query result set

//Traversal result set
                    while(cursor.moveToNext()) {

                        //db.getString(0);This parameter is passed into the index of the column
 //If the index of the incoming column is troublesome, you can also use getColumn Index("name")Method Gets the index of a column by its column name
                        String name=cursor.getString(cursor.getColumnIndex("name"));
                        System.out.println("name="+name);
                    }
                }

sqlite transaction


Using native SQL statements

Why close the database connection of SQL?

As shown in the figure above:
Every execution of ** helper.getReadableDatabase(); or the helper.getWritableDatabase method will connect to the database once
The connection of database is limited, too many connections will cause waste of resources, so every time we connect to the database, after the implementation of the corresponding functional modules, we must use the close() method to close the database; close the database.

More specific sqlite details the portal: http://www.runoob.com/w3cnote/android-tutorial-sqlite-intro.html

Topics: Database Android SQLite SQL