Android advanced 1, sqlite database

After we have learned the basic use of Android, we need to develop to a higher place. After all, water flows to a higher place. Many times we learn a technology and feel that we have no gains because we have not yet reached that level. When you go up step by step When you are learning, you will gradually find that you have gained more and more, and your progress will be faster and faster, so let’s not talk nonsense and return to the topic;

1. Understand the database

The database sqlite in Android is a miniature, cross-platform and weakly typed database. Its size is very small, only a few hundred kb. We can find it under the Android SDK folder:

 In fact, it is not the same as some mainstream database mysql. It can store different data types in a column, but its sql language is the same;

In this position, we can open cmd, and then enter sqlite3 to execute a command-line database operator. It should be noted that some of his commands are different. Compared with other databases, he creates or opens the database. It is .open, under every database command, you need to add a dot in front, and under every sql command, you need to add a semicolon after it;

.open StudentInfo

I remember that sql server and MySQL use the database name to open the database, but this is not the case here, and this small point cannot be forgotten; there are many database commands, such as exit:

.exit
.quit

Use .table to view all tables under the current database;

pragma table_info(表名)

This can view the data table structure;

For the sql statement, I believe everyone has been in contact with it more or less, so I won’t go into details here;

When we installed Android studio, we already had this database. It is no problem to store some simple data;

2. Use the database

We can download a sqlite visualization tool on the Internet to see the tables in the database:  

Many databases have their own visual management tools, MySQL has navicat, sql server has MMSM;

sqlite is sqlitestudio. After installation, we only need to drag the database we created into this program and it will open:

· Create helper classes

Of course, if we only use sqlitestudio, it is useless. We need to add, delete, modify and check data by typing codes. Android provides several classes to help us realize these operations:

We mainly understand two important classes

1)、SQLiteOpenHelper

This is a help abstract class, there is no instance, we can instantiate a subclass by inheritance:

package com.example.apptest01;

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

public class SqliteHelper extends SQLiteOpenHelper {
    private String CREATE_TABLE_STUDENTINFI="CREATE TABLE Users(" +
            "userId integer primary key AutoIncrement, userName text,age integer,passWord text)";
    public SqliteHelper(Context context){
        //参数:上下文、数据库名、工厂类、版本
        super(context,"StudentInfo.db",null,1);

    }
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(CREATE_TABLE_STUDENTINFI);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

This subclass needs to create a database and inherit the construction method of the parent class. First, you need to write a construction method, pass in the context, super the construction method of the parent class, and then use the interface method oncreate to execute the sql command to create the data table;

2)、SQLiteDatabase

This is a tool class for sql to implement addition, deletion, modification and query. You can implement sql operations through the following methods of this class, but this class needs to be obtained through the helper class:

sqliteHelper = new SqliteHelper(this);
       sqLiteDatabasewriter = sqliteHelper.getWritableDatabase();
       sqLiteDatabaseReader = sqliteHelper.getReadableDatabase();
//条件删除
sqLiteDatabasewriter.delete("Users","userId=?",new String[]{id+""});
//修改
 sqLiteDatabasewriter.update("Users",contentValues,"userId=?",new String[]{cid});
//添加
sqLiteDatabasewriter.insert("Users",null,contentValues);
//查询
sqLiteDatabasewriter.query("Users",null,"userId=?",new String[]{arrayList.get(i)+""},

· Inquire

Then we know that by creating a helper class to create an execution class, and then using the execution class to realize the addition, deletion, modification and query of data, here we first explain the specific implementation process through query:

 cursor = sqLiteDatabasewriter.query("Users",null,"userId=?",new String[]{arrayList.get(i)+""},
                null,null,null);
                if(cursor.moveToNext()){
                    id = cursor.getInt(cursor.getColumnIndex("userId"));
                    name = cursor.getString(cursor.getColumnIndex("userName"));
                    pwd = cursor.getString(cursor.getColumnIndex("passWord"));
                    age = cursor.getInt(cursor.getColumnIndex("age"));
                }

There are two ways for us to obtain the operation class, one is reader and the other is writer. Since we are querying data here, we can use reader. Of course, using writer is also harmless;

Use the query method to query data. It has some parameters. The first is the table name, and the second is the column name. Let’s understand this:

There are grouping, paging, sorting, filtering, and many parameters, but generally we just use the option selection and table name;

Its return value is a cursor object, which is equivalent to a pointer, and the query result set can be obtained through while traversal;

Regarding the cursor object, we need to be clear about its two methods, gettype() and getColumnIndex("column name"). The function of the former is to query specific data through the return value of the latter, and the latter is to query through the column name Record the corresponding index, that is to say, the combination of the two can realize the query to the specific data, of course, this needs to be realized in the while traversal;

· Add to

Adding data is also combined with the use of this operation class:

ContentValues contentValues = new ContentValues();;

contentValues.clear();
        contentValues.put("userId",et_id.getText().toString());
        contentValues.put("userName",et_name.getText().toString());
        contentValues.put("passWord",et_password.getText().toString());
        contentValues.put("age",et_age.getText().toString());
        long result = sqLiteDatabasewriter.insert("Users",null,contentValues);

        if(result == 1){
            Toast.makeText(this,"记录完成",Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(this,"记录失败",Toast.LENGTH_LONG).show();
        }

        showData();
        arrayAdapter.notifyDataSetChanged();

A new object is used here, which is ContentValues. This object is used to store key-value pairs. Through the put method, the data corresponding to the column name in the data table is stored, and then the data can be successfully inserted by using the insert method of the operation class. added to the data table;

Here you need to pay attention to the three parameters of insert, the first is the table name, the second is generally null, and the third is the key-value pair data, which use the contentvalues ​​object uniformly;

· delete

The delete operation is also used in combination with this operation class:

sqLiteDatabasewriter.delete("Users","userId=?",new String[]{id+""});

 Here we should pay attention to how to use the option whereClause is actually a condition, which corresponds to where in sql, can you use a placeholder? way, and then new String[]{} to pass parameters later, it can also be done in one step;

· Adapter review

Here we need to review the adapter. Our adapter is used to display data on the interface, so how do we refresh the display when the data changes?

arrayAdapter.notifyDataSetChanged();

Just call this method, remember that the object storing data is a global variable;

We probably use these database operations. Of course, we use more additions, deletions, modifications, and queries. Why use adapters?

Remember the adapter we talked about before, it is used to display data on the page, because after we get the data from the database, we need to display it on the page after all, so the database is an indispensable object;

Guess you like

Origin blog.csdn.net/aiwanchengxu/article/details/127155333