任何程序离不了数据,因此数据存储是个非常重要的环节。
android中进行数据存储有三种方式,一种是文件存储,一种是SharedPreferences,最后一种就是SQLiteDatabase.下面来看下怎样使用SQLiteDatabase.
1.首先要创建一个类,该类继承自android.database.sqlite.SQLiteOpenHelper,由于这个是abstract class, 因此你需要实现该类的两个方法,一个是onCreate(),一个是onUpgrade().注:两个方法的参数都省略了。
示例如下:
[java] view plain copy print ?
- public class MySQLhelper extends SQLiteOpenHelper {
- public static final String tableName = "localContact";
- public static final String ID = "_id";
- public static final String nameRow = "name";
- public static final String numRow = "mobileNum";
- public MySQLhelper(Context context, String name, CursorFactory factory, int version) {
- super(context, name, factory, version);
- }
- @Override
- public void onCreate(SQLiteDatabase db) {
- db.execSQL("CREATE TABLE IF NOT EXISTS "+tableName+" ("+nameRow+" VARCHAR,"+numRow+" VARCHAR)");
- }
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
-
- db.execSQL("DROP TABLE IF EXISTS " + tableName);
- onCreate(db);
- }
- }
public class MySQLhelper extends SQLiteOpenHelper { public static final String tableName = "localContact"; public static final String ID = "_id"; public static final String nameRow = "name"; public static final String numRow = "mobileNum"; public MySQLhelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE IF NOT EXISTS "+tableName+" ("/*+ID+" INTEGER PRIMARY KEY,"*/+nameRow+" VARCHAR,"+numRow+" VARCHAR)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // 删除以前的旧表,创建一张新的空表 db.execSQL("DROP TABLE IF EXISTS " + tableName); onCreate(db); } }
2.在activity中,创建一个MySQLhelper的实例
[c-sharp] view plain copy print ?
- MySQLhelper sqlHelper = new MySQLhelper(this,DBname,null,1);
- SQLiteDatabase sql = sqlHelper.getWritableDatabase();
MySQLhelper sqlHelper = new MySQLhelper(this,DBname,null,1); SQLiteDatabase sql = sqlHelper.getWritableDatabase();
此时便获得了刚刚创建的数据库实例的写入权限。
3.通过调用相应的方法如Insert(),delete()等,对数据库进行插入和删除的操作
4.示例:例如进行插入操作时,可以直接调用Insert()方法,代码如下:
[java] view plain copy print ?
- ContentValues tcv = new ContentValues();
- tcv.put(MySQLhelper.nameRow, name);
- tcv.put(MySQLhelper.numRow, mobilePhone);
- sql.insert(MySQLhelper.tableName, null, tcv);
ContentValues tcv = new ContentValues(); tcv.put(MySQLhelper.nameRow, name); tcv.put(MySQLhelper.numRow, mobilePhone); sql.insert(MySQLhelper.tableName, null, tcv);
也可以通过直接执行SQL语句的方式来插入,
[java] view plain copy print ?
- sql.execSQL("INSERT INTO "+MySQLhelper.tableName+" ("+MySQLhelper.nameRow+","+MySQLhelper.numRow+") VALUES ('"+name+"','"+mobilePhone+"')");
sql.execSQL("INSERT INTO "+MySQLhelper.tableName+" ("+MySQLhelper.nameRow+","+MySQLhelper.numRow+") VALUES ('"+name+"','"+mobilePhone+"')");
两种方式最后的效果都是一样的,其他的操作都类似,不一一列举。