现在的主流移动设备像Android、iPhone等都使用SQLite作为复杂数据的存储引擎,在我们为移动设备开发应用程序时,也许就要使用到SQLite来存储我们大量的数据,所以我们就需要掌握移动设备上的SQLite开发技巧。对于Android平台来说,系统内置了丰富的API来供开发人员操作SQLite,我们可以轻松的完成对数据的存取。 下面就向大家介绍一下SQLite常用的操作方法,为了方便,我将代码写在了Activity的onCreate中: [java] view plaincopyprint?
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //打开或创建test.db数据库 SQLiteDatabase db = openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null); db.execSQL("DROP TABLE IF EXISTS person"); //创建person表 db.execSQL("CREATE TABLE person (_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age SMALLINT)"); Person person = new Person(); person.name = "john"; person.age = 30; //插入数据 db.execSQL("INSERT INTO person VALUES (NULL, ?, ?)", new Object[]{person.name, person.age}); person.name = "david"; person.age = 33; //ContentValues以键值对的形式存放数据 ContentValues cv = new ContentValues(); cv.put("name", person.name); cv.put("age", person.age); //插入ContentValues中的数据 db.insert("person", null, cv); cv = new ContentValues(); cv.put("age", 35); //更新数据 db.update("person", cv, "name = ?", new String[]{"john"}); Cursor c = db.rawQuery("SELECT * FROM person WHERE age >= ?", new String[]{"33"}); while (c.moveToNext()) { int _id = c.getInt(c.getColumnIndex("_id")); String name = c.getString(c.getColumnIndex("name")); int age = c.getInt(c.getColumnIndex("age")); Log.i("db", "_id=>" + _id + ", name=>" + name + ", age=>" + age); } c.close(); //删除数据 db.delete("person", "age < ?", new String[]{"35"}); //关闭当前数据库 db.close(); //删除test.db数据库// deleteDatabase("test.db"); } 在执行完上面的代码后,系统就会在/data/data/[PACKAGE_NAME]/databases目录下生成一个“test.db”的数据库文件 上面的代码中基本上囊括了大部分的数据库操作;对于添加、更新和删除来说,我们都可以使用 [java] view plaincopyprint?
db.executeSQL(String sql);db.executeSQL(String sql, Object[] bindArgs);//sql语句中使用占位符,然后第二个参数是实际的参数集除了统一的形式之外,他们还有各自的操作方法: [java] view plaincopyprint?
|
原文地址:点击打开链接