什么是SQLite
SQLite 是一种开源的无需安装和管理配置的数据库引擎。它不需要服务器的支持,并且有事务处理的功能。SQLite不占用太大的空间,数据库支持强大的数据存储在移动以及嵌入式应用程序中。
什么是adb
Android Debug Bridge (adb) is a versatile command line tool that lets you communicate with an emulator instance or connected Android-powered device. It is a client-server program that includes three components:
Android Debug Bridge(adb)是一个可以与模拟器实例或者安卓设备通信的通用命令行工具。它是一个包含三个一下组件的客户-服务器程序。
· A client, which runs on your development machine. You can invoke a client from a shell by issuing an adb command. Other Android tools such as the ADT plugin and DDMS also create adb clients.
组件一:运行在开发机器上的客户端,你可以发出adb命令来从shell 中调用客户端。其他安卓工具比如ADT插件还有DDMS 同样能够创建adb客户端.
· A server, which runs as a background process on your development machine. The server manages communication between the client and the adb daemon running on an emulator or device.
组件二:作为后台进程运行在开发机器上的服务器。这个服务器管理运行在模拟器与设备之上的客户机以及adb守护进程之间的通信.
· A daemon, which runs as a background process on each emulator or device instance.(daemon : is a computer program that runs as a background process, rather than being under the direct control of an interactive user)
组件三:一个守护运行在每个模拟器或者设备实例上的后台进程(守护进程运行在计算机上的后台进程,而不受交互用户控制).
怎么找到adb tool
adb tool 在你安装SDK位置下的/platform-tools/下
创建并且链接到数据库中
首先导入android.database.sqlite.SQLiteDatabase 到工程中。然后调用openOrCreateDatabase() 函数来创建并连接到数据库。
package higherpass.TestingData;
import android.app.Activity;
import android.os.Bundle;
import android.database.sqlite.SQLiteDatabase;
public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db;
db = openOrCreateDatabase(
"TestingData.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
}
}
方法openOrCreateDatabase()参数除了第一个需要添加的数据库的名称之外,接着的参数便是打开数据库的权限,还有一个可选的参数cursor factory builder(游标生成器工厂)
SQLite数据库存储在哪里
SQLite数据库存储在/data/data/[application package name]/databases.
Google Android SDK 携带一个实用工具adb,想必有写过一两个Android Project都知道adb是什么吧。adb 可以被用来浏览甚至修改Android工程中附带的模拟器以及物理设备的文件系统。接下来我们开始设置数据库的具体内容:
设置数据库的各项属性
这里有几个数据库的属性需要我们去设置它们,在连接到数据库之后,即是在调用完openOrCreateDatabase()方法后,我们需要调用setVersion(),setLocale(), setLockingEnabled()方法来设置属性,这些将显示在创建表的示例中。
创建表
通过在数据库中执行语句来创建表。之后使用execSQL()来执行查询.
package higherpass.TestingData;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.database.sqlite.SQLiteDatabase;
public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db;
db = openOrCreateDatabase(
"TestingData.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
final String CREATE_TABLE_COUNTRIES =
"CREATE TABLE tbl_countries ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "country_name TEXT);";
final String CREATE_TABLE_STATES =
"CREATE TABLE tbl_states ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "state_name TEXT,"
+ "country_id INTEGER NOT NULL CONSTRAINT "
+ "country_id REFERENCES tbl_countries(id) "
+ "ON DELETE CASCADE);";
db.execSQL(CREATE_TABLE_COUNTRIES);
db.execSQL(CREATE_TABLE_STATES);
final String CREATE_TRIGGER_STATES =
"CREATE TRIGGER fk_insert_state BEFORE "
+ "INSERT on tbl_states"
+ "FOR EACH ROW "
+ "BEGIN "
+ "SELECT RAISE(ROLLBACK, 'insert on table "
+ ""tbl_states" voilates foreign key constraint "
+ ""fk_insert_state"') WHERE (SELECT id FROM "
+ "tbl_countries WHERE id = NEW.country_id) IS NULL; "
+ "END;";
db.execSQL(CREATE_TRIGGER_STATES);
}
}
我们需要手动创建触发器来处理表之间的外键关系。在应用程序中我们仍然需要创建外键触发器处理列的更新与删除操作。外键触发器也同创建表一样通过execSQL()执行。
插入记录
安卓附带了一系列简化数据库操作的类。ContentValues实例化对象构造的一系列表字符将会被传入insert() 方法用于数据匹配。安卓同样也创造了类似的方法用于更新和删除记录。
ContentValues values = new ContentValues();
values.put("country_name", "US");
long countryId = db.insert("tbl_countries", null, values);
ContentValues stateValues = new ContentValues();
stateValues.put("state_name", "Texas");
stateValues.put("country_id", Long.toString(countryId));
try {
db.insertOrThrow("tbl_states", null, stateValues);
} catch (Exception e) {
//catch code
}
将这些代码追加到先前的例子当中去。首先创建一个ContentValues对象来存储将要插入表的数据,并使用put() 方法来加载数据进去。然后我们使用insert() 方法向SQLite中传入相关参数。insert() 函数除了三个参数,the table name, null, the ContentValues name 之外,还有一个长整形返回值,该返回值是一个ID,the row ID of the newly inserted row,新插入行的行ID.
ContentValues stateValues = new ContentValues();
stateValues.put("state_name", "Texas");
stateValues.put("country_id", Long.toString(countryId));
这里我们使用了insertOrThrow() 方法,这个方法呢在插入不成功的情况下就会抛出一个exception,而且这个方法必须被包含在try/catch 块中。你会发现现在应用程序推出一个不可控制的exception,这是因为我们试着去创建的表已经存在了。所以我们应当返回到adb shell 然后连接到SQLite数据库中删除表。
下面是删除表的具体操作:
1、用adb.exe查找正在运行的设备(至少要打开一个模拟器)
E:\android-sdk-windows\platform-tools\adb devices
List of devices attached
emulator-5554 device
2、如果模拟器没有运行,使用以下命令启动
E:\android-sdk-windows\tools\emulator.exe @avdname
3、查看虚拟设备,使用以下命令启动
E:\android-sdk-windows\tools\android list avd
Available Android Virtual Devices:
Name: 2_3_3
Path: C:\Documents and Settings\Administrator.android\avd\2_3_3.avd
Target: Android 2.3.3 (API level 10)
Skin: 320x533
Sdcard: 50M
4、在连接的设备上打开一个shell
E:\android-sdk-windows\platform-tools\adb shell
5、查看自己的数据库
# ls -R /data/data/*/databases
———-
/data/data/cn.edu.xtu.tilepuzzle/databases/DBTilePuzzle.db
/data/data/higherpass.TestingData/databases/TestingData.db
6、找到自己的数据库
/data/data/higherpass.TestingData/databases/TestingData.db
7、打开数据库
# sqlite3 /data/data/cn.edu.xtu.tilepuzzle/databases/DBTilePuzzle.db
8、删除数据库存在的表
sqlite> drop table tbl_countries;
sqlite> drop table tbl_states;
更新数据
更新数据我们可以使用update() 方法。这个函数跟其他数据库引擎一样同样支持WHERE 语法。这个方法除了the table name, a ContentValues 实例与insert() 中的ContentValues 字段相似。同样允许可选的WHERE 语法,添加一个包含WHERE语句的字符串作为第三个参数。使用? 可以指定第四个参数以数组形式作为替代参数传递WHERE字句。
ContentValues updateCountry = new ContentValues();
updateCountry.put(“country_name”, “United States”);
db.update(“tbl_countries”, updateCountry, “id=?”, new String[] {Long.toString(countryId)});
首先我们从代码中移除表的创建语句,我们不需要一直创建和删除表。我们创建一个新的ContextValues实例,updateCountry,去存放要更新的数据。然后我们使用update()方法来更新表。这里参数三使用了?来把数值存放在参数四中。如果多?存放在WHERE语句中,那么我们应该按顺序将值放在数组中。
删除数据
一旦数据不需要时我们可以使用delete() 方法从数据库中删除它。这个方法包含三个参数,the database name, a WHERE clause, an argument array for the WHERE clause.想要删除整个表的话第三个参数以及第四个参数传递为null,也就是WHERE子句以及带有WHERE子句的字符串数组。
db.delete(“tb1_table”, “id=?”, new String[]{Long.toString(countryid)});
删除方法中的第三以及第四个参数仅仅是个配合而已,因为第三个参数中的? 其实就是代替了第四个参数,因为这样方便些,不会导致第三个参数过长,这样也方便程序员修改。
检索数据
从SQLite数据库中检索数据的话要使用到Cursors.SQLite查询的结果存储在一个由查询相关方法返回的Cursor对象中。要使用Cursor需要导入android.database.Cursor这个包。