一、 SQLiteDatabase的常用方法
openOrCreateDatabase(String path,SQLiteDatabase.CursorFactory factory)//打开或创建数据库
insert(String table,String nullColumnHack,ContentValues values)//插入一条记录
delete(String table,String whereClause,String[] whereArgs)//删除一条记录
query(String table,String[] columns,String selection,String[] selectionArgs,String groupBy,String having,String orderBy)//查询一条记录
update(String table,ContentValues values,String whereClause,String[] whereArgs)//修改记录
execSQL(String sql)//执行一条SQL语句
close()//关闭数据库
二、SQLiteDatabase的操作
1. 打开或者创建数据库
在Android 中使用SQLiteDatabase的静态方法openOrCreateDatabase(String path,SQLiteDatabae.CursorFactory factory)打开或者创建一个数据库。它会自动去检测是否存在这个数据库,如果存在则打开,不存在则创建一个数据库;创建成功则返回一个SQLiteDatabase对象,否则抛出异常FileNotFoundException。
下面是创建名为“book.db”数据库的代码:
openOrCreateDatabase(String path,SQLiteDatabae.CursorFactory factory)
参数1 数据库创建的路径
参数2 一般设置为null就可以了
db=SQLiteDatabase.openOrCreateDatabase("book.db",null);
2、创建表
创建一张表的步骤很简单:
编写创建表的SQL语句
调用SQLiteDatabase的execSQL()方法来执行SQL语句
下面的代码创建了一张用户表,属性列为:id(主键并且自动增加)、sname(学生姓名)、snumber(学号)
private void createTable(SQLiteDatabase db){
//创建表SQL语句
public static final String CREATE_BOOK = "create table book ("
+ "id integer primary key autoincrement, "
+ "author text, "
+ "price real, "
+ "pages integer, "
+ "name text)";
//执行SQL语句
db.execSQL(CREATE_BOOK );
}
3、插入数据
插入数据有两种方法:
①SQLiteDatabase的insert(String table,String nullColumnHack,ContentValues values)方法,
参数1 表名称,
参数2 空列的默认值
参数3 ContentValues类型的一个封装了列名称和列值的Map;
②编写插入数据的SQL语句,直接调用SQLiteDatabase的execSQL()方法来执行
第一种方法的代码:
private void insert(SQLiteDatabase db){
//实例化常量值
ContentValues cValue = new ContentValues();
//添加用户名
cValue.put("sname","xiaoming");
//添加密码
cValue.put("snumber","01005");
//调用insert()方法插入数据
db.insert("stu_table",null,cValue);
}
第二种方法的代码:
private void insert(SQLiteDatabase db){
//插入数据SQL语句
String stu_sql="insert into stu_table(sname,snumber) values('xiaoming','01005')";
//执行SQL语句
db.execSQL(sql);
}
4、删除数据
删除数据也有两种方法:
①调用SQLiteDatabase的delete(String table,String whereClause,String[] whereArgs)方法
参数1 表名称
参数2 删除条件
参数3 删除条件值数组
②编写删除SQL语句,调用SQLiteDatabase的execSQL()方法来执行删除。
第一种方法的代码:
private void delete(SQLiteDatabase db) {
//删除条件
String whereClause = "id=?";
//删除条件参数
String[] whereArgs = {String.valueOf(2)};
//执行删除
db.delete("stu_table",whereClause,whereArgs);
}
第二种方法的代码:
private void delete(SQLiteDatabase db) {
//删除SQL语句
String sql = "delete from stu_table where _id = 6";
//执行SQL语句
db.execSQL(sql);
}
5、修改数据
修改数据有两种方法:
①调用SQLiteDatabase的update(String table,ContentValues values,String whereClause, String[] whereArgs)方法
参数1 表名称
参数2 跟行列ContentValues类型的键值对Key-Value
参数3 更新条件(where字句)
参数4 更新条件数组
②编写更新的SQL语句,调用SQLiteDatabase的execSQL执行更新。
第一种方法的代码:
private void update(SQLiteDatabase db) {
//实例化内容值 ContentValues values = new ContentValues();
//在values中添加内容
values.put("snumber","101003");
//修改条件
String whereClause = "id=?";
//修改添加参数
String[] whereArgs={String.valuesOf(1)};
//修改
db.update("usertable",values,whereClause,whereArgs);
}
第二种方法的代码:
private void update(SQLiteDatabase db){
//修改SQL语句
String sql = "update stu_table set snumber = 654321 where id = 1";
//执行SQL
db.execSQL(sql);
}
6、查询数据
在Android中查询数据是通过Cursor类来实现的,当我们使用SQLiteDatabase.query()方法时,会得到一个Cursor对象,Cursor指向的就是每一条数据。它提供了很多有关查询的方法,具体方法如下:
public Cursor query(String table,String[] columns,String selection,String[] selectionArgs,String groupBy,String having,String orderBy,String limit);
各个参数的意义说明:
参数table:表名称
参数columns:列名称数组
参数selection:条件字句,相当于where
参数selectionArgs:条件字句,参数数组
参数groupBy:分组列
参数having:分组条件
参数orderBy:排序列
参数limit:分页查询限制
参数Cursor:返回值,相当于结果集ResultSet
Cursor是一个游标接口,提供了遍历查询结果的方法,如移动指针方法move(),获得列值方法getString()等.
Cursor游标常用方法
getCount()//获得总的数据项数
isFirst()//判断是否第一条记录
isLast()//判断是否最后一条记录
moveToFirst()//移动到第一条记录
moveToLast()//移动到最后一条记录
move(int offset)//移动到指定记录
moveToNext()//移动到下一条记录
moveToPrevious()//移动到上一条记录
getColumnIndexOrThrow(String columnName)//根据列名称获得列索引
getInt(int columnIndex)//获得指定列索引的int类型值
getString(int columnIndex)//获得指定列缩影的String类型值
三、 SQLiteDatabase的操作Demo
1. SQLiteOpenHelper类
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String CREATE_BOOK = "create table book ("
+ "id integer primary key autoincrement, "
+ "author text, "
+ "price real, "
+ "pages integer, "
+ "name text)";
private Context mContext;
public MySQLiteHelper(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_BOOK);
Toast.makeText(mContext,"创建成功",Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
}
2. xml布局文件
3. Activity
public class MainActivity extends AppCompatActivity {
private TextView mTvDatainfo;
private Button mBtnCreate;
private Button mBtnInsert;
private Button mBtnDelete;
private Button mBtnUpdate;
private Button mBtnQuery;
private Button mBtnDestroy;
private SQLiteDatabase db;
private MySQLiteHelper mySQLiteHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
mySQLiteHelper = new MySQLiteHelper (MainActivity.this,"book",null,1);
initView ();
setListener ();
}
public void initView(){
mTvDatainfo = (TextView)findViewById (R.id.tv_database_info);
mTvDatainfo.setMovementMethod (ScrollingMovementMethod.getInstance ());
mBtnCreate = findViewById (R.id.btn_database_create);
mBtnInsert = findViewById (R.id.btn_database_insert);
mBtnDelete = findViewById (R.id.btn_database_delete);
mBtnUpdate = findViewById (R.id.btn_database_update);
mBtnQuery = findViewById (R.id.btn_database_query);
mBtnDestroy = findViewById (R.id.btn_database_destroy);
}
private void setListener(){
mBtnCreate.setOnClickListener (new CreateListener ());
mBtnInsert.setOnClickListener (new InsertListener ());
mBtnDelete.setOnClickListener (new DeleteListener ());
mBtnUpdate.setOnClickListener (new UpdateListener ());
mBtnQuery.setOnClickListener (new QueryListener ());
//mBtnDestroy.setOnClickListener (new DestroyListener ());
}
class CreateListener implements View.OnClickListener{
@Override
public void onClick(View view) {
db = mySQLiteHelper.getWritableDatabase ();
mTvDatainfo.setText ("创建数据库成功!");
}
}
class InsertListener implements View.OnClickListener{
@Override
public void onClick(View view) {
insertData ("曹雪芹",40,400,"《红楼梦》");
insertData ("吴承恩",50,410,"《西游记》");
insertData ("罗贯中",45,500,"《三国演义》");
insertData ("施耐庵",56,524,"《水浒传》");
mTvDatainfo.setText ("添加数据成功!");
}
}
class DeleteListener implements View.OnClickListener{
@Override
public void onClick(View view) {
String whereClauses = "id=?";
String [] whereArgs = {String.valueOf(1)};
db.delete ("book",whereClauses,whereArgs);
mTvDatainfo.setText ("删除成功!");
}
}
class UpdateListener implements View.OnClickListener{
@Override
public void onClick(View view) {
ContentValues cv = new ContentValues ();
cv.put ("author","ColdPlay");
cv.put ("name","A Head Full of Dream");
String whereClauses = "id=?";
String [] whereArgs = {String.valueOf(1)};
db.update ("book",cv,whereClauses,whereArgs);
mTvDatainfo.setText ("修改成功!");
}
}
class QueryListener implements View.OnClickListener{
@Override
public void onClick(View view) {
String[] strings = new String[]{"id","author","price","pages","name"};
mTvDatainfo.setText ("");
db = mySQLiteHelper.getReadableDatabase ();
Cursor cursor = db.query ("book",strings,null,null,null,null,null);
for (int i = 0; i < cursor.getCount (); i++) {
if(cursor.moveToFirst ()) {
cursor.move (i);
int id = cursor.getInt (cursor.getColumnIndex ("id"));
Log.d ("book id", "book is NO." + id);
String author = cursor.getString (cursor.getColumnIndex ("author"));
int price = cursor.getInt (cursor.getColumnIndex ("price"));
int pages = cursor.getInt (cursor.getColumnIndex ("pages"));
String name = cursor.getString (cursor.getColumnIndex ("name"));
mTvDatainfo.append ("book id is: " +id + "\n"
+ "author is: " + author + "\n"
+ "price is: " + price + "\n"
+ "pages is: " + pages + "\n"
+ "book name is: " + name+"\n"
+ "\n");
}
}
}
}
class DestroyListener implements View.OnClickListener{
@Override
public void onClick(View view) {
db = mySQLiteHelper.getWritableDatabase ();
String sql ="DROP TABLE book";
db.execSQL(sql);
mTvDatainfo.setText ("删除表成功!");
}
}
public void insertData(String author, int price, int pages, String name){
ContentValues cv = new ContentValues ();
cv.put ("author",author);
cv.put ("price",price);
cv.put ("pages",pages);
cv.put ("name",name);
db.insert ("book",null,cv);
mTvDatainfo.setText ("添加数据成功!");
}
}