对于android而言,它为我们提供了一个十分强大的轻量级数据库。该数据库基本可以满足我们的需求,下面我们就来讲解一下SQLiteOpenHelper
以及SQLiteDatabase
的用法: 由于 SQLiteOpenHelper
是一个抽象类,所以我们要用一个实现类来实现它,旗下有两个方法需要我们适当的加入相应的逻辑,分别是oncrecate
和onupgrade
方法。 当然,SQLiteOpenHelper
中 还 有 两 个 非 常 重 要 的 实 例方 法 , getReadableDatabase()
和getWritableDatabase()
。这两个方法都可以创建或打开一个现有的数据库(如果数据库已存在则直接打开,否则创建一个新的数据库) ,并返回一个可对数据库进行读写操作的对象。不同的是当数据库不可写入的时候(如磁盘空间已满)getReadableDatabase()
方法返回的对象将以只读的方## 标题 ##式去打开数据库,而 getWritableDatabase()
方法则将出现异常。 下面,我们就通过代码来更深层次的来探讨,新建一个类MyDatabaseHelper
使他继承SQLiteOpenHelper
类,代码如下:
public class MyDatabaseHelper extends SQLiteOpenHelper {
public static final String CREATE_BOOK = "create table Book ("
+ "id integer primary key autoincrement, "
+ "author text, "
+ "price real, "
+ "pages integer, "
+ "name text)";
public static final String CREATE_CATEGORY = "create table Category ("
+ "id integer primary key autoincrement, "
+ "category_name text, "
+ "category_code integer)";
public MyDatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL( CREATE_BOOK);
db.execSQL( CREATE_CATEGORY);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//更新版本
db.execSQL( "drop table if exists Book");
db.execSQL( "drop table if exists Category" );
onCreate(db);
}
}
*
首先我们建立了两条sql语句,分别创建了Book表和Catagory表,接着,将其逻辑赋值在oncreate方法中,则只要该类一经调用,便会去发现它,然后去判断是否该数据库已经存在该表格,若存在,不创建,若不存在,创建,及表只会别创建一次。我们再来看看onupgrade这个方法,用于表只会创建一次,但如果我们后面由于要加入新的需求怎么办,那么这时候就要用到这个onupgrade方法了,只需将其内置的版本号调为比当前版本号大即可执行到里面的逻辑。
*
一下是我们的 MainActivity中的主要逻辑。
public class MainActivity extends Activity {
private MyDatabaseHelper dbHelper ;//通过DatabaseHelper来操作数据
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout. activity_main);
dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);//创建数据库
Button createDatabase = (Button) findViewById(R.id. create_database);
createDatabase.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
dbHelper.getWritableDatabase(); //开始读写操作
}
});
Button addData = (Button) findViewById(R.id. add_data);
addData.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();//用于存取数据
values.put( "name", "The Da Vinci Code" );
values.put( "author", "Dan Brown" );
values.put( "pages", 454);
values.put( "price", 16.96);
db.insert( "Book", null , values);
values.clear(); //清空数据
values.put( "name", "The Lost Symbol" );
values.put( "author", "Dan Brown" );
values.put( "pages", 510);
values.put( "price", 19.95);
db.insert( "Book", null , values);//插入数据到数据库中
}
});
Button updateData = (Button) findViewById(R.id. update_data);
updateData.setOnClickListener( new OnClickListener() {//更新数据
@Override
public void onClick(View v) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put( "price", 10.99);
db.update( "Book", values, "name = ?" ,
new String[] { "The Da Vinci Code" });
}
});
Button deleteButton = (Button) findViewById(R.id. delete_data);//删除数据
deleteButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete( "Book", "pages > ?" , new String[] { "500" });
}
});
Button queryButton = (Button) findViewById(R.id. query_data);//查询数据
queryButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = Uri
. parse("content://com.example.databasetest.provider/book");
Cursor cursor = getContentResolver().query(uri, null, null,
null, null );
if (cursor != null) {
while (cursor.moveToNext()) {
String name = cursor.getString(cursor
.getColumnIndex( "name"));
String author = cursor.getString(cursor
.getColumnIndex( "author"));
int pages = cursor.getInt(cursor
.getColumnIndex( "pages"));
double price = cursor.getDouble(cursor
.getColumnIndex( "price"));
Log. d("MainActivity", "book name is " + name);
Log. d("MainActivity", "book author is " + author);
Log. d("MainActivity", "book pages is " + pages);
Log. d("MainActivity", "book price is " + price);
}
cursor.close();
}
}
});
Button replaceData = (Button) findViewById(R.id. replace_data);//对数据库进行事物处理
replaceData.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction();
try {
db.delete( "Book", null , null);
// if (true) {
// throw new NullPointerException();
// }
ContentValues values = new ContentValues();
values.put( "name", "Game of Thrones" );
values.put( "author", "George Martin" );
values.put( "pages", 720);
values.put( "price", 20.85);
db.insert( "Book", null , values);
db.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
db.endTransaction();
}
}
});
}
}
*在这个类中,我想你也大概能看得懂,其主要是做了增删改查的操作,通过 SQLiteDatabase 这个类来实现,这里由于和java对数据库中的操作大同小异就不在进行废话,更多详情,你可以去看第一行代码中的介绍。
下面是我们的activity_main.xml的代码:*
<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_database"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Create database" />
<Button
android:id="@+id/add_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add data" />
<Button
android:id="@+id/update_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Update data" />
<Button
android:id="@+id/delete_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Delete data" />
<Button
android:id="@+id/query_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Query data" />
<Button
android:id="@+id/replace_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Replace data" />
</LinearLayout>