android SQLite

来源:互联网 发布:京都小众景点.知乎 编辑:程序博客网 时间:2024/06/07 04:42

SQLite的特性:

轻量级 使用 SQLite 只需要带一个动态库,就可以享受它的全部功能,而且那个动态库的尺寸想当小。 

独立性 SQLite 数据库的核心引擎不需要依赖第三方软件,也不需要所谓的“安装”。 

隔离性 SQLite 数据库中所有的信息(比如表、视图、触发器等)都包含在一个文件夹内,方便管理和维护。 

跨平台 SQLite 目前支持大部分操作系统

多语言接口 SQLite 数据库支持多语言编程接口。 

安全性 SQLite 数据库通过数据库级上的独占性和共享锁来实现独立事务处理。这意味着多个进程可以在同一时间从同

一数据库读取数据,但只能有一个可以写入数据.

优点:

1.能存储较多的数据。

2.能将数据库文件存放到SD卡中!


SQLiteDatabase:

SQLiteDatabase 的实例代表了一个SQLite 的数据库,通过SQLiteDatabase 实例的一些方法,我们可以执行SQL 语

句,对数据库进行增、删、查、改的操作。需要注意的是,数据库对于一个应用来说是私有的,并且在一个应用当中,

数据库的名字也是惟一的。

Android SQLiteDatabase对数据的操作方法有两种:

sqlDatabase.execSQL(String sql)

Android对应的方法


ContentValues

ContentValues 类和Hashmap/Hashtable 比较类似,它也是负责存储一些名值对,但是它存储的名值对当中的名是一

个String 类型,而值都是基本类型。

public long insert(People people) {ContentValues newValues = new ContentValues();newValues.put(KEY_NAME, people.Name);newValues.put(KEY_AGE, people.Age);newValues.put(KEY_HEIGHT, people.Height);return db.insert(DB_TABLE, null, newValues);}

Cursor类:

理解和使用 Android Cursor 的几件事情:

Cursor 是每行的集合。 

使用 moveToFirst() 定位第一行。 

你必须知道每一列的名称。 

你必须知道每一列的数据类型。 

Cursor 是一个随机的数据源。 

所有的数据都是通过下标取得


SQLiteDatabase 提供了如下静态方法来打开一个文件对应的数据库:

static SQLiteDatabase openDatabase(String path,SQLiteDatabase.CursorFactory factory,int flags):打开path文件所代表的SQLite数据库

static SQLiteDatabase openOrCreateDatabase(File file,SQLiteDatabase.CursorFactory factory):打开或创建(如果不存在)file文件所代表的SQLite数据库

static SQLiteDatabase openOrCreateDatabase(String path,SQLiteDatabase.CursorFactory factory): 打开或创建(如果不存在)path文件所代表的SQLite数据库


获取了SQLiteDatabase对象后,接下来就可调用SQLiteDatabase的如下方法来操作数据库了:

void execSQL(String sql,Object[] bindArgs):执行带占位符的SQL语句

void execSQL(String sql):执行SQL语句

insert(String table,String nullColumnHack,ContentValues values):向执行表中插入数据

update(String table,ContentValues values,String whereClause,String[] whereArgs):更新指定表中的特定数据

delete(String table,String whereClause,String[] whereArgs):删除指定表中的特定数据

Cursor query(String table,String[] columns,String whereClause,String[] whereArgs,String groupBy,String having,String orderBy):对执行数据表执行查询

Cursor query(String table,String[] columns,String whereClause,String[] whereArgs,String groupBy,String having,String orderBy,String limit):对执行数据表执行查询。limit 参数控制最多查询几条记录(用于控制分页的参数)

rawQuery(String sql,String[] selectionArgs):执行带占位符的SQL查询

beginTransaction():开始事务

endTransaction():结束事务


Cursor提供了如下方法来移动查询结果的指针:

move(int offset):将记录指针向上或向下移动指定的行数。offset为正数就是向下移动,为负数就是向上移动。

boolean moveToFirst():将记录指针移动到第一行,如果移动成功则返回true。

boolean moveToLast():将记录指针移动到最后一行,如果移动成功则返回true。

boolean moveToNext():将记录指针移动到下一行,如果移动成功则返回true。

moveToPrevious()//移动光标到上一行

boolean moveToPosition(int position):将记录指针移动到指定的行,如果移动成功则返回

getColumnCount()//返回所有列的总数

getCount()//返回Cursor 中的行数

getColumnIndex(String columnName) 返回指定列的名称,如果不存在返回-1

getColumnIndexOrThrow(String columnName) 从零开始返回指定列名称,如果不存在将抛出IllegalArgumentException 异常。

getColumnName(int columnIndex)//从给定的索引返回列名

getColumnNames()//返回一个字符串数组的列名

copyStringToBuffer(int columnIndex, CharArrayBuffer buffer) 在缓冲区中检索请求的列的文本,将将其存储

close() //关闭游标,释放资源


用SQLiteDatabase进行数据库操作的步骤如下:

获取SQLiteDatabase对象,它代表了与数据库的连接

调用SQLiteDatabase的方法来执行SQL语句

操作SQL语句的执行结果,比如用SimpleCursorAdapter封装Cursor

关闭SQLiteDatabase,回收资源


SQLiteDatabase中包含如下两个方法来控制事务:

beginTransaction():开始事务

endTransaction():结束事务

inTransaction():如果当前上下文处于事务中,则返回true,否则返回false

setTransactionSuccessfun()方法来设置事务标志,如果程序事务执行中调用该方法设置了事务成功则提交事务,否则程序将会回滚事务

实例代码如下:

db.beginTransaction();try{//执行DML语句...//调用该方法设置事务成功,否则endTransaction()方法将回滚事务}finally{//由事务的标志决定是否是提交事务还是回滚事务db.endTransaction();}

SQLiteOpenHelper类:

SQLiteOpenHelper是Android提供的一个管理数据库的工具类,可用于管理数据库的创建和版本更新。SQLiteOpenHelper 是一个抽象类,一般的用法是创建SQLiteOpenHelper的子类,并扩展它的onCreate(SQLiteDatabase db),onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion)方法和构造函数方法。

SQLiteOpenHelper包含如下常用的方法:

synchronized SQLiteDatabase getReadableDatabase():以读写的方式打开数据库对应的SQLiteDatabase对象

synchronized SQLiteDatabase getWritableDatabase():以写的方式打开数据库对应的SQLiteDatabase对象

abstract void onCreate(SQLiteDatabase db):当第一次创建数据库时回调该方法

abstract void onUpgrade(SQLiteDatabase db,int oldVersion,int new Version):当数据库版本更新时回调该方法

synchronized void close():关闭所有打开的SQLiteDatabase


注意:

使用SimpleCursorAdapter封装Cursor时要求底层数据表的主键列的列名为_id,因为SimpleCursorAdapter只能识别列名为_id的主键。

SQLite内部只支持NULL,INTEGER,REAL(浮点数),TEXT(文本)和BLOB(大二进制对象)这5种数据类型,但实际上SQLite完全可以接收varchar(n),char(n),decimal(p,s)等数据类型,只不过SQLite会在运算或保存时将它们转换为上面5种数据类型。

SQLite允许把各种类型的数据保存到任何类型字段中,开发者可以不用关心声明该字段所使用的数据类型。例如,可以把字符串的值存入INTEGER类型的字段中。但有一种情况例外:定义为INTEGER PRIMARY KEY的字段只能存储64位整数,当向这种字段保存除整数以外类型的数据时,会产生错误。


例子代码如下:

model:

public class People {public int ID = -1;public String Name;public int Age;public float Height;@Overridepublic String toString(){String result = "";result += "ID:" + this.ID + ",";result += "姓名:" + this.Name + ",";result += "年龄:" + this.Age + ", ";result += "身高:" + this.Height + ",";return result;}}

service:

import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteException;import android.database.sqlite.SQLiteOpenHelper;import android.database.sqlite.SQLiteDatabase.CursorFactory;public class DBAdapter {private static final String DB_NAME = "people.db";private static final String DB_TABLE = "peopleinfo";private static final int DB_VERSION = 1; public static final String KEY_ID = "_id";public static final String KEY_NAME = "name";public static final String KEY_AGE = "age";public static final String KEY_HEIGHT = "height";private SQLiteDatabase db;private final Context context;private DBOpenHelper dbOpenHelper;public DBAdapter(Context _context) {    context = _context;  }  /** Close the database */  public void close() {  if (db != null){  db.close();  db = null;  }}  /** Open the database */  public void open() throws SQLiteException {    dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);  try {  db = dbOpenHelper.getWritableDatabase();  }  catch (SQLiteException ex) {  db = dbOpenHelper.getReadableDatabase();  }  }    public long insert(People people) {    ContentValues newValues = new ContentValues();      newValues.put(KEY_NAME, people.Name);    newValues.put(KEY_AGE, people.Age);    newValues.put(KEY_HEIGHT, people.Height);        return db.insert(DB_TABLE, null, newValues);  }  public People[] queryAllData() {    Cursor results =  db.query(DB_TABLE, new String[] { KEY_ID, KEY_NAME, KEY_AGE, KEY_HEIGHT},   null, null, null, null, null);  return ConvertToPeople(results);     }    public People[] queryOneData(long id) {    Cursor results =  db.query(DB_TABLE, new String[] { KEY_ID, KEY_NAME, KEY_AGE, KEY_HEIGHT},   KEY_ID + "=" + id, null, null, null, null);  return ConvertToPeople(results);     }    private People[] ConvertToPeople(Cursor cursor){  int resultCounts = cursor.getCount();  if (resultCounts == 0 || !cursor.moveToFirst()){  return null;  }  People[] peoples = new People[resultCounts];  for (int i = 0 ; i<resultCounts; i++){  peoples[i] = new People();  peoples[i].ID = cursor.getInt(0);  peoples[i].Name = cursor.getString(cursor.getColumnIndex(KEY_NAME));  peoples[i].Age = cursor.getInt(cursor.getColumnIndex(KEY_AGE));  peoples[i].Height = cursor.getFloat(cursor.getColumnIndex(KEY_HEIGHT));    cursor.moveToNext();  }    return peoples;   }    public long deleteAllData() {  return db.delete(DB_TABLE, null, null);  }  public long deleteOneData(long id) {  return db.delete(DB_TABLE,  KEY_ID + "=" + id, null);  }  public long updateOneData(long id , People people){  ContentValues updateValues = new ContentValues();    updateValues.put(KEY_NAME, people.Name);  updateValues.put(KEY_AGE, people.Age);  updateValues.put(KEY_HEIGHT, people.Height);    return db.update(DB_TABLE, updateValues,  KEY_ID + "=" + id, null);  }  /** 静态Helper类,用于建立、更新和打开数据库*/  private static class DBOpenHelper extends SQLiteOpenHelper {  public DBOpenHelper(Context context, String name, CursorFactory factory, int version) {    super(context, name, factory, version);  }  private static final String DB_CREATE = "create table " +     DB_TABLE + " (" + KEY_ID + " integer primary key autoincrement, " +    KEY_NAME+ " text not null, " + KEY_AGE+ " integer," + KEY_HEIGHT + " float);";  @Override  public void onCreate(SQLiteDatabase _db) {    _db.execSQL(DB_CREATE);  }  @Override  public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {        _db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);    onCreate(_db);  }}}

Activity:

import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;public class SQLiteDemo extends Activity {    /** Called when the activity is first created. */private DBAdapter dbAdepter ;private EditText nameText;private EditText ageText;private EditText heightText;private EditText idEntry;private TextView labelView;private TextView displayView;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                nameText = (EditText)findViewById(R.id.name);        ageText = (EditText)findViewById(R.id.age);        heightText = (EditText)findViewById(R.id.height);        idEntry = (EditText)findViewById(R.id.id_entry);                labelView = (TextView)findViewById(R.id.label);        displayView = (TextView)findViewById(R.id.display);                                Button addButton = (Button)findViewById(R.id.add);        Button queryAllButton = (Button)findViewById(R.id.query_all);              Button clearButton = (Button)findViewById(R.id.clear);        Button deleteAllButton = (Button)findViewById(R.id.delete_all);                Button queryButton = (Button)findViewById(R.id.query);        Button deleteButton = (Button)findViewById(R.id.delete);        Button updateButton = (Button)findViewById(R.id.update);                        addButton.setOnClickListener(addButtonListener);         queryAllButton.setOnClickListener(queryAllButtonListener);             clearButton.setOnClickListener(clearButtonListener);        deleteAllButton.setOnClickListener(deleteAllButtonListener);                      queryButton.setOnClickListener(queryButtonListener);        deleteButton.setOnClickListener(deleteButtonListener);        updateButton.setOnClickListener(updateButtonListener);                dbAdepter = new DBAdapter(this);        dbAdepter.open();    }        OnClickListener addButtonListener = new OnClickListener() {@Overridepublic void onClick(View v) {People people = new People();people.Name = nameText.getText().toString();people.Age = Integer.parseInt(ageText.getText().toString());people.Height = Float.parseFloat(heightText.getText().toString());long colunm = dbAdepter.insert(people);if (colunm == -1 ){labelView.setText("添加过程错误!");} else {labelView.setText("成功添加数据,ID:"+String.valueOf(colunm));nameText.setText("");ageText.setText("");heightText.setText("");}}    };        OnClickListener queryAllButtonListener = new OnClickListener() {@Overridepublic void onClick(View v) {People[] peoples = dbAdepter.queryAllData();if (peoples == null){labelView.setText("数据库中没有数据");return;}labelView.setText("数据库:");String msg = "";for (int i = 0 ; i<peoples.length; i++){msg += peoples[i].toString()+"\n";}displayView.setText(msg);}    };        OnClickListener clearButtonListener = new OnClickListener() {@Overridepublic void onClick(View v) {displayView.setText("");}    };        OnClickListener deleteAllButtonListener = new OnClickListener() {@Overridepublic void onClick(View v) {dbAdepter.deleteAllData();String msg = "数据全部删除";labelView.setText(msg);}    };        OnClickListener queryButtonListener = new OnClickListener() {@Overridepublic void onClick(View v) {int id = Integer.parseInt(idEntry.getText().toString());People[] peoples = dbAdepter.queryOneData(id);if (peoples == null){labelView.setText("数据库中没有ID为"+String.valueOf(id)+"的数据");return;}labelView.setText("数据库:");displayView.setText(peoples[0].toString());}    };        OnClickListener deleteButtonListener = new OnClickListener() {@Overridepublic void onClick(View v) {long id = Integer.parseInt(idEntry.getText().toString());long result = dbAdepter.deleteOneData(id);String msg = "删除ID为"+idEntry.getText().toString()+"的数据" + (result>0?"成功":"失败");labelView.setText(msg);}    };        OnClickListener updateButtonListener = new OnClickListener() {@Overridepublic void onClick(View v) {People people = new People();people.Name = nameText.getText().toString();people.Age = Integer.parseInt(ageText.getText().toString());people.Height = Float.parseFloat(heightText.getText().toString());long id = Integer.parseInt(idEntry.getText().toString());long count = dbAdepter.updateOneData(id, people);if (count == -1 ){labelView.setText("更新错误!");} else {labelView.setText("更新成功,更新数据"+String.valueOf(count)+"条");}}    };}


效果图:


官方文档:http://developer.android.com/training/basics/data-storage/databases.html#DefineContract

中文翻译:http://www.cnblogs.com/mengdd/archive/2013/05/02/3055465.html


0 0
原创粉丝点击