一.定义
SQLite是一款轻量级的关系型数据库,运算速度快,占用资源少,通常只需要几百KB的内存就足够了。SQLite支持标准的SQL语法,遵循数据库的ACID事务。SQLite不需要设置账户名和密码就可以使用,比一般的数据库要简单得多。
二.适用范围
存储大量复杂的关系型数据
三.数据库创建
为了能够更加方便地管理数据库,Android提供了一个SQLiteOpenHelper帮助类,通过该类可以非常简单的创建和升级数据库。
1.在SQLiteOpenHelper继承类中,创建一个名叫User的表,定义名字、身高、年龄。
public static final String CREATE_USER = "Create table User("
+"id integer primary key autoincrement,"
+"name text,"
+"height real,"
+"age integer)";
建表语句中,关键字"autoincrement"表示自动递增,"primary key"表示主键,"id integer primary key autoincrement"表示id列是自增长的整数主键,integer 表示整型,text表示文本类型,real表示浮点型。
- User创建完成,使用execSQL()方法来执行该建表语句
@Override
public void onCreate(SQLiteDatabase db){
db.execSQL(CREATE_USER);
}
3.构建SQLiteOpenHelper的实例,调用getWritableDatabase()或getReadableDatabase()方法创建数据库
dataBaseHelper = new DataBaseHelper(this,"UserDataBase.db",null,1);
dataBaseHelper.getWritableDatabase();
DataBaseHelper是SQLiteOpenHelper继承类中构建的方法,第一个参数为上下文Context;第二个参数为自定义数据库名称;第三个参数为自定义的factory,当数据库进行查询时由该factory产生一个返回的Cursor;第四个参数为版本号。
四.升级数据库
1.在UserDataBase.db数据库中新增一个名叫UserCategory的表,定义地址、国籍
public static final String CREATE_USERCATEGORY = "Create table UserCategory("
+"id integer primary key autoincrement,"
+"address text,"
+"Country text)";
- UserCategory创建完成,使用execSQL()方法来执行该建表语句
@Override
public void onCreate(SQLiteDatabase db){
db.execSQL(CREATE_USERCATEGORY);
}
3.因为UserDataBase.db数据库已经存在了,所以SQLiteOpenHelper继承类中的onCreate()不会再次执行。我们可以通过卸载程序,然后重新运行来解决;当然我们也可以通过修改代码来解决。使用"drop table if exists"语句来删除表,在重新调用onCreate()方法创建表
@Override
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
db.execSQL("drop table if exists User");
db.execSQL("drop table if exists UserCategory");
onCreate(db);
}
修改构建SQLiteOpenHelper的实例传入的版本号
dataBaseHelper = new DataBaseHelper(this,"UserDataBase.db",null,2);
dataBaseHelper.getWritableDatabase();
五.数据库的添查改删(CRUD)
Android提供了名为SQLiteDatabase的类,该类封装了一些操作数据库的API,我们可以使用该类对数据库进行添加(Create)、查询(Retrieve)、更新(Update)和删除(Delete)操作,即CRUD。使用ContentValues来对数据进行组装。
1.添加(Create)
SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
//开始组装第一条数据
values.put("name","浅若清风");
values.put("height",165);
values.put("age",31);
//插入第一条数据
db.insert("User",null,values);
//开始组装第二条数据
values.put("name","浅若清风1");
values.put("height",166);
values.put("age",32);
//插入第二条数据
db.insert("User",null,values);
使用insert()方法将数据添加到表中。insert()方法接收三个参数,第一个参数传入表名(需要添加数据的表名);第二个参数用于在未指定添加数据的情况下给某些可为空的列自动赋值NULL,一般传入null即可;第三个参数为ContentValues对象,使用其的put()方法添加数据。
2.更新(Update)
SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("age",18);
db.update("User",values,"name=?",new String[]{"浅若清风"});
使用update()方法进行数据更新。update()方法接收四个参数,第一个参数传入表名(需要更新数据的表名);第二个参数为ContentValues对象,使用其的put()方法组装新数据;第三和第四个参数用于约束更新哪些行的数据,不指定就默认为更新所有行。
3.删除(Delete)
SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("age",18);
db.delete("User","age>?",new String[]{"18"});
使用delete()方法进行数据删除。delete()方法接收三个参数,第一个参数传入表名(需要删除数据的表名);第二和第三个参数用于约束删除哪些行的数据,不指定就默认为删除所有行。
4.查询(Retrieve)
SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
//查询User表中的所有数据
Cursor cursor = db.query("User",null,null,null,null,null,null);
if (cursor.moveToFirst()){
do {
//遍历Cursor对象,取出数据
String name = cursor.getString(cursor.getColumnIndex("name"));
double height = cursor.getDouble(cursor.getColumnIndex("height"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
}while (cursor.moveToNext());
}
cursor.close();
使用query()方法进行数据查询。query()方法至少接收7个参数:
//七个参数
query(String table, String[] columns, String selection,String[] selectionArgs, String groupBy, String having,String orderBy)
//八个参数
query(String table, String[] columns, String selection,String[] selectionArgs, String groupBy, String having,String orderBy, String limit)
第一个参数传入表名(需要查询数据的表名);第二个参数用于约束查询哪些列,不指定就默认查询所有列;第三和第四个参数用于约束查询哪些行的数据,不指定就默认为查询所有行;第五个参数用于指定需要通过[参数五]去分组的列,不指定就表示不对查询结果进行分组操作;第六个参数用于对通过[参数五]分组后的数据进行过滤,不指定就表示不进行过滤;第七个参数用于指定查询结果的排序方式,不知道就使用默认排序方式;第八个参数表示分页查询限制。
完整示例代码
//继承于SQLiteOpenHelper的类
public class DataBaseHelper extends SQLiteOpenHelper {
//创建User表
public static final String CREATE_USER = "Create table User("
+"id integer primary key autoincrement,"
+"name text,"
+"height real,"
+"age integer)";
//创建User_1表
public static final String CREATE_USER_1 = "Create table User_1("
+"id integer primary key autoincrement,"
+"name_1 text,"
+"height_1 real,"
+"age_1 integer)";
private Context mContext;
//第一个参数为上下文Context;第二个参数为自定义数据库名称;第三个参数为自定义的factory,当数据库进行查询时由该factory产生一个返回的Cursor;第四个参数为版本号
public DataBaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,int version){
super(context,name,factory,version);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db){
db.execSQL(CREATE_USER);
db.execSQL(CREATE_USERCATEGORY);
Toast.makeText(mContext,"Create succeeded",Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
//使用drop table if exists语句删除表
db.execSQL("drop table if exists User");
db.execSQL("drop table if exists UserCategory");
//重新调用建表语句
onCreate(db);
}
}
//.java实现
//声明
private DataBaseHelper dataBaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//升级数据库修改版本号
dataBaseHelper = new DataBaseHelper(this,"UserDataBase.db",null,1);
//创建数据库
Button createBtn = findViewById(R.id.create_data);
createBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dataBaseHelper.getWritableDatabase();
}
});
//添加数据
Button addBtn = findViewById(R.id.add_data);
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
//开始组装第一条数据
values.put("name","浅若清风");
values.put("height",165);
values.put("age",31);
//插入第一条数据
db.insert("User",null,values);
//开始组装第二条数据
values.put("name","浅若清风1");
values.put("height",166);
values.put("age",32);
//插入第二条数据
db.insert("User",null,values);
}
});
//更新数据
Button updateBtn = findViewById(R.id.update_data);
updateBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("age",18);
db.update("User",values,"name=?",new String[]{"浅若清风"});
}
});
//删除数据
Button deleteBtn = findViewById(R.id.delete_data);
deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("age",18);
db.delete("User","age>?",new String[]{"18"});
}
});
//查询数据
Button retrieveBtn = findViewById(R.id.retrieve_data);
retrieveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
//查询User表中的所有数据
Cursor cursor = db.query("User",null,null,null,null,null,null);
if (cursor.moveToFirst()){
do {
//遍历Cursor对象,取出数据
String name = cursor.getString(cursor.getColumnIndex("name"));
double height = cursor.getDouble(cursor.getColumnIndex("height"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
}while (cursor.moveToNext());
}
cursor.close();
}
});
}
<!--xml布局-->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!--创建数据库按钮-->
<Button
android:id="@+id/create_data"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="Create"
/>
<!--添加数据按钮-->
<Button
android:id="@+id/add_data"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="Add"
/>
<!--更新数据按钮-->
<Button
android:id="@+id/update_data"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="Update"
/>
<!--删除数据按钮-->
<Button
android:id="@+id/delete_data"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="Delete"
/>
<!--查询数据按钮-->
<Button
android:id="@+id/retrieve_data"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="Retrieve"
/>
</LinearLayout>
对数据库的添查改删(CRUD),也可以直接使用SQL语句来操作数据库











网友评论