在编程中常常会遇到数据库的操作,而Android系统内置了SQLite,它是一款轻型数据库,遵守事务ACID的关系型数据库管理系统,它占用的资源非常低,可以支持Windows/Linux/Unix等主流操作系统,同一时候可以跟非常多程序语言如C#、PHP、Java等相结合.以下先回想SQL的基本语句,再讲述Android的基本操作.
一. adb shell回想SQL语句
首先,我感觉自己整个大学印象最深的几门课就包含《数据库》,所以想先回想SQL增删改查的基本语句.而在Android SDK中adb是自带的调试工具,它存放在sdk的platform-tools文件夹下,通过adb shell能够进入设备控制台,操作SQL语句.
G:
cd G:\software\Program software\Android\adt-bundle-windows-x86_64-20140321\sdk\platform-tools
adb shell
cd /data/data/com.example.sqliteaction/databases/
sqlite3 StuDatabase.db
.table
.schema例如以下所看到的我先创建了SQLiteActionproject,同一时候在project中创建了StuDatabase.db数据库.输入adb shell进入设备控制台,调用"sqlite3+数据库名"打开数据库,假设没有db文件则创建.
然后例如以下图所看到的,能够输入SQL语句运行增删改查.注意非常easy写错SQL语句,如忘记")"或结束";"导致cmd中调用出错.
--创建Teacher表
create table Teacher (id integer primary key, name text);
--向表中插入数据
insert into Teacher (id,name) values('10001', 'Mr Wang');
insert into Teacher (id,name) values('10002', 'Mr Yang');
--查询数据
select * from Teacher;
--更新数据
update Teacher set name='Yang XZ' where id=10002;
--删除数据
delete from Teacher where id=10001;
二. SQLite数据库操作
以下解说使用SQLite操作数据库: 1.创建打开数据库
使用openOrCreateDatabase函数实现,它会自己主动检測是否存在该数据库,假设存在则打开,否则创建一个数据库,并返回一个SQLiteDatabase对象.
2.创建表
通过定义建表的SQL语句,再调用execSQL方法运行该SQL语句实现建立表.
//创建学生表(学号,姓名,电话,身高) 主键学号
public static final String createTableStu = "create table Student (" +
"id integer primary key, " +
"name text, " +
"tel text, " +
"height real)";
//SQLiteDatabase定义db变量
db.execSQL(createTableStu);3.插入数据
使用insert方法加入数据,事实上ContentValues就是一个Map,Key字段名称,Value值.SQLiteDatabase.insert(
String table, //加入数据的表名
String nullColumnHack,//为某些空的列自己主动复制NULL
ContentValues values //ContentValues的put()方法加入数据
);
//方法一
SQLiteDatabase db = sqlHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("id", "10001");
values.put("name", "Eastmount");
values.put("tel", "15201610000");
values.put("height", "172.5");
db.insert("Student", null, values);
//方法二
public static final String insertData = "insert into Student (" +
"id, name, tel, height) values('10002','XiaoMing','110','175')";
db.execSQL(insertData);4.删除数据
使用delete方法删除表中数据,当中sqlHelper是继承SQLiteDatabase自己定义类的实例.SQLiteDatabase.delete(
String table, //表名
String whereClause, //约束删除行,不指定默认删除全部行
String[] whereArgs //相应数据);
//方法一 删除身高>175cm
SQLiteDatabase db = sqlHelper.getWritableDatabase();
db.delete("Student", "height > ?", new String[] {"175"});
//方法二
String deleteData = "DELETE FROM Student WHERE height>175";
db.execSQL(deleteData);5.更新数据使用update方法能够改动数据,SQL+execSQL方法就不在叙述.//小明的身高改动为180
SQLiteDatabase db = sqlHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("height", "180");</