SQLite数据库是开源嵌入式数据库,支持的数据库大小为2TB. SQLite具有以下几个特征:
SQLite操作的核心类是SQLiteDatabase与SQLiteOpenHelper。
Android系统提供了SQLiteOpenHelper的抽象类,通过继承它对数据库版本进行管理。 用以在安装或升级软件时自动创建数据库。
/*
@param context to use for locating paths to the the database
@param name of the database file, or null for an in-memory database
@param factory to use for creating cursor objects, or null for the default
@param version number of the database (starting at 1); if the database is older,
*/
public SQLOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
官方文档注释:
构造方法的参数为context数据库的存储路径,无需做更改。 String name 数据库的名称。 factory可以直接为空。 version即数据库版本号。
@Override
public void onCreate(SQLiteDatabase db) {
}
用以在初次使用软件时创建数据库。
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
用以更新数据库,会自动检测版本号是否改变,改变则自动更新。执行更新数据库的操作。当软件的版本升级次数比较多时,在onUpgrade()方法里面可以根据原版本号和目标版本号进行判断,然后做出相应的表结构及数据更新。
getWritableDatabase()方法,以读写方式打开数据库。一旦数据库的磁盘空间满了,则打开数据库时会出错。
getReadableDatabase()方法先以读写的方式打开数据库,如果数据库磁盘空间满了就会打开失败,打开失败后尝试以只读的方式打开。 更不容易出错。
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String USER_TABLE_NAME = "user";
public static final String USERNAME = "username";
public static final String AGE = "age";
public static final String DATABASE_NAME = "test.db";
/*
* @param context to use for locating paths to the the database
* @param name of the database file, or null for an in-memory database
* @param factory to use for creating cursor objects, or null for the default
* @param version number of the database (starting at 1); if the database is older,
*/
//构造方法 创建一个数据库 文件名为test.db
public DatabaseHelper(@Nullable Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
//创建一个名为user的数据库,里面存放数据username password
db.execSQL("create table " + USER_TABLE_NAME + "(" + USERNAME + " varchar(20) not null, " + AGE + " varchar(60) not null);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
SQLiteDatabase类封装了一i邪恶操作数据库的API,使用该类对数据库进行增删改查操作
获取SQLiteDatabase类的对象要通过SQLiteOpenHelper调用getWritableDatabase方法,代码如下
声明变量:
public SQLiteDatabase mSQLiteDatabase;
获取SQLiteDatabase对象
DatabaseHelper databaseHelper = new DatabaseHelper(this); //调用数据库
mSQLiteDatabase = databaseHelper.getWritableDatabase();
API文档中的代码:
/**
* Convenience method for inserting a row into the database.
*
* @param table the table to insert the row into
* @param nullColumnHack optional; may be null
.
* SQL doesn't allow inserting a completely empty row without
* naming at least one column name. If your provided values
is
* empty, no column names are known and an empty row can't be inserted.
* If not set to null, the nullColumnHack
parameter
* provides the name of nullable column name to explicitly insert a NULL into
* in the case where your values
is empty.
* @param values this map contains the initial column values for the
* row. The keys should be the column names and the values the
* column values
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long insert(String table, String nullColumnHack, ContentValues values) {
try {
return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
} catch (SQLException e) {
Log.e(TAG, "Error inserting " + values, e);
return -1;
}
}
使用insert实现增加数据的操作。
传递的第一参数是将要操作的数据表的名称。即我们在创建一个数据库时给起的table名,下图中圈出部分
传递的第三个参数 就是要增加的字段,可以是多个字段,用ContentValues来存放。
传递的第二个参数的作用是保证每一个insert操作都能完成,当传递的第三个参数为空时才需要指定,当第三个参数不为空时,第二个参数为null
示例代码
//Add操作
findViewById(R.id.add_but).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues contentValues3 = new ContentValues();
contentValues3.put(DatabaseHelper.USERNAME,"王三");
contentValues3.put(DatabaseHelper.AGE,"18");
//mSQLiteDatabase.insert(DatabaseHelper.USER_TABLE_NAME,null,contentValues3);
long rowNumber = mSQLiteDatabase.insert(DatabaseHelper.USER_TABLE_NAME, null, contentValues3);
if(rowNumber !=-1){
Toast.makeText(DatabaseButtonActivity.this,"插入成功",Toast.LENGTH_SHORT).show();
}
}
});
API文档中的代码,建议好好看看注释部分:
/**
* Convenience method for deleting rows in the database.
*
* @param table the table to delete from
* @param whereClause the optional WHERE clause to apply when deleting.
* Passing null will delete all rows.
* @param whereArgs You may include ?s in the where clause, which
* will be replaced by the values from whereArgs. The values
* will be bound as Strings.
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise. To remove all rows and get a count pass "1" as the
* whereClause.
*/
public int delete(String table, String whereClause, String[] whereArgs) {
acquireReference();
try {
SQLiteStatement statement = new SQLiteStatement(this, "DELETE FROM " + table +
(!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs);
try {
return statement.executeUpdateDelete();
} finally {
statement.close();
}
} finally {
releaseReference();
}
}
第一个参数表示的是要执行操作的表,
第二个参数用来过滤不需要的值或者选择适当的要素,
第三个参数用于给第二个参数的占位符提供数据,其中第二个参数可以有多个条件。
示例代码:
findViewById(R.id.delete_but).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String whereClauseString = "username = ?"; //定义删除的条件,我们要删除的是username等于这个问好的条件
//String[] whereArgsString = {"王三"}; //定义代替问号条件的数组,当username等于王三时,删除数据
String[] whereArgsString = {deleteText.getText().toString()};
mSQLiteDatabase.delete(DatabaseHelper.USER_TABLE_NAME,whereClauseString,whereArgsString);
}
});
代码中的whereClauseString 相当于一个判定条件,用以判断需要删除哪些字段的数据。有的时候我们需要一次性删除的数据不止一条,所以用字符串数组来存储需要删除的字段名。这样就有了whereArgsString数组。前面的问号就是占位符,需要whereArgsString来补充。
数据库查询结果的返回值并不是数据集合的完整复制,而是返回数据集的指针,这个指针就是Cursor类。
Cursor类的方法。
API文档中的代码及注释
/**
* Query the given table, returning a {@link Cursor} over the result set.
*
* @param table The table name to compile the query against.
* @param columns A list of which columns to return. Passing null will
* return all columns, which is discouraged to prevent reading
* data from storage that isn't going to be used.
* @param selection A filter declaring which rows to return, formatted as an
* SQL WHERE clause (excluding the WHERE itself). Passing null
* will return all rows for the given table.
* @param selectionArgs You may include ?s in selection, which will be
* replaced by the values from selectionArgs, in order that they
* appear in the selection. The values will be bound as Strings.
* @param groupBy A filter declaring how to group rows, formatted as an SQL
* GROUP BY clause (excluding the GROUP BY itself). Passing null
* will cause the rows to not be grouped.
* @param having A filter declare which row groups to include in the cursor,
* if row grouping is being used, formatted as an SQL HAVING
* clause (excluding the HAVING itself). Passing null will cause
* all row groups to be included, and is required when row
* grouping is not being used.
* @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
* (excluding the ORDER BY itself). Passing null will use the
* default sort order, which may be unordered.
* @return A {@link Cursor} object, which is positioned before the first entry. Note that
* {@link Cursor}s are not synchronized, see the documentation for more details.
* @see Cursor
*/
public Cursor query(String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having,
String orderBy) {
return query(false, table, columns, selection, selectionArgs, groupBy,
having, orderBy, null /* limit */);
}
第一个参数就是数据表table名,
第二个是需要查询的字段,是一个字符串数组。
第三个参数是筛选条件,相当于删除操作中定义的whereClauseString。有问号?占位符
第四个参数是第三个参数的补充,用以补充问号部分。三四两个参数同有同无。
示例代码:
findViewById(R.id.query_but).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String[] colu = {"王三"};
Cursor cursor = mSQLiteDatabase.query(DatabaseHelper.USER_TABLE_NAME, null,
"username = ?",colu,null,null,null);
// columns 是控制字段约束,控制查询取出哪些字段。
if(cursor.moveToFirst()){
int count = cursor.getCount();
for(int i=0;i<count;i++){
String userName = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.USERNAME));
String age = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.AGE));
Log.i(MainActivity.class.getSimpleName(),i + ":" + userName + "|" + age +"." );
}
}
}
});
改即更改数据库中原本有的字段数据,就是更新操作。所以需要一个ContentValues来存储新的数据,
需要找到是哪一个字段,哪一条数据进行修改,这是就需要查找条件。
API文档中的代码注释
/**
* Convenience method for updating rows in the database.
*
* @param table the table to update in
* @param values a map from column names to new column values. null is a
* valid value that will be translated to NULL.
* @param whereClause the optional WHERE clause to apply when updating.
* Passing null will update all rows.
* @param whereArgs You may include ?s in the where clause, which
* will be replaced by the values from whereArgs. The values
* will be bound as Strings.
* @return the number of rows affected
*/
public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
return updateWithOnConflict(table, values, whereClause, whereArgs, CONFLICT_NONE);
}
第一参数 table名
第二个参数 更新的数据
第三四个参数代更新数据的查找条件。
示例代码:
findViewById(R.id.update_but).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.AGE,"100岁");
String whereClauseString = "username=?";
String[] whereArgsString = {updateText.getText().toString()};
mSQLiteDatabase.update(DatabaseHelper.USER_TABLE_NAME,contentValues,whereClauseString,whereArgsString);
}
});
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String USER_TABLE_NAME = "user";
public static final String USERNAME = "username";
public static final String AGE = "age";
public static final String DATABASE_NAME = "test.db";
/*
* @param context to use for locating paths to the the database
* @param name of the database file, or null for an in-memory database
* @param factory to use for creating cursor objects, or null for the default
* @param version number of the database (starting at 1); if the database is older,
*/
//构造方法 创建一个数据库 文件名为test.db
public DatabaseHelper(@Nullable Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
//创建一个名为user的数据库,里面存放数据username password
db.execSQL("create table " + USER_TABLE_NAME + "(" + USERNAME + " varchar(20) not null, " + AGE + " varchar(60) not null);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
/**
* 在这个Activity中调用DatabaseHelper类创建一个数据库,并且实现增删改查的操作
*/
public class DatabaseButtonActivity extends AppCompatActivity {
public SQLiteDatabase mSQLiteDatabase;
EditText addText, addAge,deleteText, queyText, updateText;
ContentValues contentValues = new ContentValues();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
DatabaseHelper databaseHelper = new DatabaseHelper(this); //调用数据库
mSQLiteDatabase = databaseHelper.getWritableDatabase();
//Add操作
findViewById(R.id.add_but).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues contentValues3 = new ContentValues();
contentValues3.put(DatabaseHelper.USERNAME,"王三");
contentValues3.put(DatabaseHelper.AGE,"18");
//mSQLiteDatabase.insert(DatabaseHelper.USER_TABLE_NAME,null,contentValues3);
long rowNumber = mSQLiteDatabase.insert(DatabaseHelper.USER_TABLE_NAME, null, contentValues3);
if(rowNumber !=-1){
Toast.makeText(DatabaseButtonActivity.this,"插入成功",Toast.LENGTH_SHORT).show();
}
}
});
/**
* query查询操作
* Cursor 就是一个游标,用来获取查询数据库得到的集合。
* public Cursor query(String table, String[] columns, String selection,
* String[] selectionArgs, String groupBy, String having,
* String orderBy)
*
*/
findViewById(R.id.query_but).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String[] colu = {"王三"};
Cursor cursor = mSQLiteDatabase.query(DatabaseHelper.USER_TABLE_NAME, null,
"username = ?",colu,null,null,null);
// columns 是控制字段约束,控制查询取出哪些字段。
if(cursor.moveToFirst()){
int count = cursor.getCount();
for(int i=0;i<count;i++){
String userName = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.USERNAME));
String age = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.AGE));
Log.i(MainActivity.class.getSimpleName(),i + ":" + userName + "|" + age +"." );
}
}
}
});
/**
* 删除操作
* 删除数据库中的所有数据或者某一条数据
* public int delete(String table, String whereClause, String[] whereArgs)
* @param table the table to delete from
* @param whereClause the optional WHERE clause to apply when deleting.
* Passing null will delete all rows.
* @param whereArgs You may include ?s in the where clause, which
* will be replaced by the values from whereArgs. The values
* will be bound as Strings.
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise. To remove all rows and get a count pass "1" as the
* whereClause.
*/
findViewById(R.id.delete_but).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String whereClauseString = "username = ?"; //定义删除的条件,我们要删除的是username等于这个问好的条件
//String[] whereArgsString = {"王三"}; //定义代替问号条件的数组,当username等于王三时,删除数据
String[] whereArgsString = {deleteText.getText().toString()};
mSQLiteDatabase.delete(DatabaseHelper.USER_TABLE_NAME,whereClauseString,whereArgsString);
}
});
/**
* 更新操作。 更新是对数据库中的某一条数据进行更新。 比如对数据库已经存在的网三的年龄进行更新
* @param table the table to update in
* @param values a map from column names to new column values. null is a
* valid value that will be translated to NULL.
* @param whereClause the optional WHERE clause to apply when updating.
* Passing null will update all rows.
* @param whereArgs You may include ?s in the where clause, which
* will be replaced by the values from whereArgs. The values
* will be bound as Strings.
* @return the number of rows affected
*/
findViewById(R.id.update_but).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.AGE,"100岁");
String whereClauseString = "username=?";
String[] whereArgsString = {updateText.getText().toString()};
mSQLiteDatabase.update(DatabaseHelper.USER_TABLE_NAME,contentValues,whereClauseString,whereArgsString);
}
});
button();
}
public void button(){
addText = findViewById(R.id.text_input);
addAge = findViewById(R.id.num_input);
deleteText = findViewById(R.id.text_input_delete);
queyText = findViewById(R.id.text_input_query);
updateText = findViewById(R.id.text_input_update);
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
<EditText
android:id="@+id/text_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:text="请输入要添加的用户名"
android:textSize="24sp"
android:textColor="@color/text_Color"
android:background="@color/editText_color"/>
<EditText
android:id="@+id/num_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:text="请输入用户年龄"
android:textSize="24sp"
android:textColor="@color/text_Color"
android:background="@color/editText_color"
android:layout_marginTop="12dp"/>
<Button
android:id="@+id/add_but"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:textSize="24sp"/>
<EditText
android:id="@+id/text_input_delete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:text="请输入要删除的用户名"
android:textSize="24sp"
android:textColor="@color/text_Color"
android:background="@color/editText_color"/>
<Button
android:id="@+id/delete_but"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="delete"
android:textSize="24sp"/>
<EditText
android:id="@+id/text_input_query"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:text="请输入要查询的用户名"
android:textSize="24sp"
android:textColor="@color/text_Color"
android:background="@color/editText_color"/>
<Button
android:id="@+id/query_but"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="query"
android:textSize="24sp"/>
<EditText
android:id="@+id/text_input_update"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:text="请输入要更新的用户名"
android:textSize="24sp"
android:textColor="@color/text_Color"
android:background="@color/editText_color"/>
<Button
android:id="@+id/update_but"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="update"
android:textSize="24sp"/>
</LinearLayout>
实际应用需要根据自己的需求去设计数据库,多练多试。
分享一个百度云课程:
链接:https://pan.baidu.com/s/1W_4WIsnf7MGKRottfp-9yw
提取码:vsgn
需要完整版的可以私聊我