Android中SQLite用法

来源:互联网 发布:ajax php 编辑:程序博客网 时间:2024/04/29 22:35

Android中SQLite用法

1.SQLite简介
SQLite一个非常流行的轻量级的嵌入式关系型数据库,它在2000年由D. Richard Hipp 发布,它支持SQL语言,并且只用很少的内存就有很好的性能,它可以减少应用程序管理数据的开销,SQLite可移植性好、很容易使用、很小、高效而且可靠。此外它还是开源的,任何人都可以使用它。许多开源项目(Mozilla,PHP,Python)都使用了SQLite。
SQLite由以下几个组件组成:SQL编译器、内核、后端以及附件。SQLite通过虚拟机和虚拟数据库引擎(VDBE),使调试、修改和扩展 SQLite的内核变得更加方便。

Android在运行时(run-time)集成了SQLite,所以每个Android应用程序都可以使用 SQLite 数据库。目前在Android 系统中集成的是SQLite3 版本,SQLite不支持静态数据类型,而是使用列关系。这意味着它的数据类型不具有表列属性,而具有数据本身的属性。当某个值插入数据库时,SQLite将检查它的类型。如果该类型与关联的列不匹配,则SQLite 会尝试将该值转换成列类型。如果不能转换,则该值将作为其本身具有的类型存储。
SQLite支持NULL、INTEGER、REAL、TEXT 和BLOB 数据类型。
例如:可以在Integer 字段中存放字符串,或者在布尔型字段中存放浮点数,或者在字符型字段中存放日期型值。但是有一种例外,如果你的主键是INTEGER,那么只能存储64位整数,当向这种字段中保存除整数以外的数据时,将会产生错误。另外, SQLite 在解析CREATE TABLE 语句时,会忽略CREATE TABLE 语句中跟在字段名后面的数据类型信息。
数据库存储在 data/data/package name/databases/数据库名称。

2.SQLite数据库特点

1)零配置
SQlite3不用安装、不用配置、不用启动、关闭或者配置数据库实例。当系统崩溃后不用做任何恢复操作,在下次使用数据库的时候自动恢复。
2)可移植
它可以运行在Windows、Linux、BSD、Mac OS X 和一些商用Unix 系统,比如Sun 的Solaris、IBM 的AIX,同样,它也可以工作在许多嵌入式操作系统下,比如Android、QNX、VxWorks、Palm OS、Symbin 和Windows CE。
3)紧凑
SQLite是被设计成轻量级、自包含的。一个头文件、一个lib 库,你就可以使用关系数据库了,不用任何启动任何系统进程。
4)简单
SQLite有着简单易用的API 接口。
5)可靠
SQLite的源码达到100%分支测试覆盖率。

3.SQLite与其它数据库的区别

SQLite基本上符合SQL-92标准,SQLite和其它数据库最大的不同就是对数据类型的支持,创建一个表时,可以在CREATE TABLE语句中指定某列的数据类型,但是你可以把任何数据类型放入任何列中。当某个值插入数据库时,SQLite将检查它的类型。如果该类型与关联的列不匹配,则SQLite会尝试将该值转换成该列的类型。如果不能转换,则该值将作为其本身具有的类型存储。比如:可以把一个字符串(String)放入INTEGER列,SQLite 称这为“弱类型”(manifest typing)。
此外,SQLite不支持一些标准的SQL功能,特别是外键约束(FOREIGN KEY constrains),嵌套 transcaction 和RIGHT OUTER JOIN和FULL OUTER JOIN,还有一些 ALTER TABLE 功能。
除了上述功能外,SQLite 是一个完整的SQL系统,拥有完整的触发器,交易等等。

4.应用场景
Android使用SQLite作为复杂数据的存储引擎,开发应用程序时,有可能就要使用到SQLite来存储大量的数据,对于Android平台来说,系统内置了丰富的API来供开发人员操作SQLite,我们可以轻松的完成对数据的存取。

5.常用语句
查询语句:
select * from 表名 where 条件子句group by 分组字句 having … order by 排序子句
分页语句:
select * from Account limit 5 offset 3 或者select * from Account limit 3,5
(错过前3行,获取之后的5条数据)
插入语句:
insert into 表名(字段列表) values(值列表)。
更新语句:
update 表名set 字段名 = 值where 条件子句。
删除语句:
delete from 表名where 条件子句。
其他语句:
c.move(int offset); //以当前位置为参考,移动到指定行
c.moveToFirst(); //移动到第一行
c.moveToLast(); //移动到最后一行
c.moveToPosition(int position);//移动到指定行
c.moveToPrevious();//移动到前一行
c.moveToNext(); //移动到下一行
c.isFirst();//是否指向第一条
c.isLast();//是否指向最后一条
c.isBeforeFirst();//是否指向第一条之前
c.isAfterLast();//是否指向最后一条之后
c.isNull(int columnIndex);//指定列是否为空(列基数为0)
c.isClosed();//游标是否已关闭
c.getCount();//总数据项数
c.getPosition();//返回当前游标所指向的行数
c.getColumnIndex(String columnName);//返回某列名对应的列索引值
c.getString(int columnIndex);//返回当前行指定列的值
最后当我们完成了对数据库的操作后,记得调用SQLiteDatabase的close()方法释放数据库连接,否则容易出现SQLiteException。
应用实例:
DatabaseHelper.java

/** * 继承SQLiteOpenHelper * * @author Harvey * */public class DatabaseHelper extends SQLiteOpenHelper{    /**     * 数据库名称 /.db可有可无     */    public static final String DATABASE_NAME = "test.db";    /**     * 数据库版本,版本号不能为0     */    public static final int DATABASE_VERSION = 1;    /**     * 构造方法     *     * @param context     */    public DatabaseHelper(Context context)    {        // CursorFactory设置为null,使用默认值        this(context, DATABASE_NAME, null, DATABASE_VERSION);    }    /**     * 必须要有此构造方法     *     * @param context     *            代表应用的上下文     * @param name     *            代表数据库的名称     * @param factory     *            代表记录集游标工厂,是专门用来生成记录集游标,记录集游标是对查询结果进行迭代的     * @param version     *            代表数据库的版本,如果以后升级软件的时候,需要更改     */    public DatabaseHelper(Context context, String name, CursorFactory factory, int version)    {        // 必须通过super调用父类当中的构造函数        super(context, name, factory, version);    }    /**     * 在用户第一次使用软件时,会创建数据库,而该方法在数据库初次创建时被调用,此方法中特别适合     * 生成数据库表的结构,它只会被调用一次,它的唯一一个参数是操作数据库的工具类,这个     * 工具类提供了对数据的添、删、改、查等方法,用这个类实现对SQL语句的执行     */    @Override    public void onCreate(SQLiteDatabase db)    {        db.execSQL("CREATE TABLE person (personid INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(20), age INTEGER)");    }    /**     * version版本号发生改变时,此方法会被调用,在这个方法中比较适合实现软件更新时修改数据库表结构的工作     */    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)    {        // 数据库更新的语句        db.execSQL("ALTER TABLE person ADD COLUMN other STRING");    } }

Person.java

public class Person{    /**     * id     */    private Integer id;    /**     * name     */    private String name;    /**     * age     */    private Integer age;    public Person()    {    }    public Integer getId()    {        return id;    }    public void setId(Integer id)    {        this.id = id;    }    public String getName()    {        return name;    }    public void setName(String name)    {        this.name = name;    }    public Integer getAge()    {        return age;    }    public void setAge(Integer age)    {        this.age = age;    }    @Override    public String toString()    {        return "id:" + id + "\nage:" + age + "\nname:" + name;    }}

SQLiteTestActivity.java(第一种方法)

/** * 数据库使用测试 * * @author admin * */public class SQLiteTestActivity extends Activity implements OnClickListener{    private Button addBtn, addListBtn, delBtn, updateBtn, queryBtn, countBtn, pagingBtn, otherBtn;    private TextView text;    private DatabaseHelper databaseHelper;    @Override    public void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        init();    }    private void init()    {        addBtn = (Button) findViewById(R.id.add);        addListBtn = (Button) findViewById(R.id.addList);        delBtn = (Button) findViewById(R.id.delete);        updateBtn = (Button) findViewById(R.id.update);        queryBtn = (Button) findViewById(R.id.query);        countBtn = (Button) findViewById(R.id.count);        pagingBtn = (Button) findViewById(R.id.paging);        otherBtn = (Button) findViewById(R.id.other);        // 设置监听        addBtn.setOnClickListener(this);        addListBtn.setOnClickListener(this);        delBtn.setOnClickListener(this);        updateBtn.setOnClickListener(this);        queryBtn.setOnClickListener(this);        countBtn.setOnClickListener(this);        pagingBtn.setOnClickListener(this);        otherBtn.setOnClickListener(this);        text = (TextView) findViewById(R.id.text);        databaseHelper = new DatabaseHelper(this);    }    @Override    public void onClick(View v)    {        /**         * 添加对象         */        if (v.equals(addBtn))        {            Person person = new Person();            person.setName("Eric");            person.setAge(23);            addData(person);        }        /**         * 添加对象集合         */        if (v.equals(addListBtn))        {            ArrayList<Person> personList = new ArrayList<Person>();            Person person = new Person();            person.setName("Tom");            person.setAge(20);            personList.add(person);            Person person1 = new Person();            person1.setName("Jack");            person1.setAge(21);            personList.add(person1);            Person person2 = new Person();            person2.setName("Harvey");            person2.setAge(22);            personList.add(person2);            addData(personList);        }        /**         * 删除数据         */        if (v.equals(delBtn))        {            deleteData(1);        }        /**         * 更新数据         */        if (v.equals(updateBtn))        {            Person person = new Person();            person.setId(2);            person.setName("Bob");            person.setAge(35);            updateData(person);        }        /**         * 查询数据         */        if (v.equals(queryBtn))        {            queryData(3);        }        /**         * 数据总数         */        if (v.equals(countBtn))        {            System.out.println("查询总数=====" + countData());        }        /**         * 分页         */        if (v.equals(pagingBtn))        {            getScrollData(0, 3);        }        if (v.equals(otherBtn))        {            other();        }    }    /**     * 添加对象     */    private void addData(Person person)    {        SQLiteDatabase db = databaseHelper.getWritableDatabase();// 创建或者打开一个可写数据库        // 插入数据        db.execSQL("INSERT INTO person(name, age) VALUES(?,?)", new Object[]        {                person.getName(), person.getAge()        });        Log.i("SQLiteTestActivity", "name:" + person.getName() + "\nage:" + person.getAge());    }    /**     * 添加对象集合     *     * @param personList     */    private void addData(ArrayList<Person> personList)    {        SQLiteDatabase db = databaseHelper.getWritableDatabase();// 创建或者打开一个可写数据库        db.beginTransaction(); // 开始事务        try        {            for (Person person : personList)            {                db.execSQL("INSERT INTO person(name, age) VALUES(?, ?)", new Object[]                {                        person.getName(), person.getAge()                });                Log.i("SQLiteTestActivity", "name:" + person.getName() + "\nage:" + person.getAge());            }            db.setTransactionSuccessful(); // 设置事务成功完成        }        finally        {            db.endTransaction(); // 结束事务        }    }    /**     * 删除数据     *     * @param id     */    private void deleteData(Integer id)    {        SQLiteDatabase db = databaseHelper.getWritableDatabase();// 创建或者打开一个可写数据库        db.execSQL("delete from person where personid=?", new Object[]        {            id        });    }    /**     * 更新数据     */    private void updateData(Person person)    {        SQLiteDatabase db = databaseHelper.getWritableDatabase();        db.execSQL("update person set name=?,age=? where personid=?", new Object[]        {                person.getName(), person.getAge(), person.getId()        });    }    /**     * 查询数据     */    private void queryData(Integer id)    {        SQLiteDatabase db = databaseHelper.getReadableDatabase();// 创建或者打开一个查询数据库        Cursor cursor = db.rawQuery("select * from person where personid=?", new String[]        {            String.valueOf(id)        });        // 迭代记录集        if (cursor.moveToNext())        {            Person person = new Person();            person.setId(cursor.getInt(cursor.getColumnIndex("personid")));            person.setName(cursor.getString(cursor.getColumnIndex("name")));            person.setAge(cursor.getInt(cursor.getColumnIndex("age"))); // 将查到的字段,放入person            System.out.println(person.toString());            text.setText(person.toString());        }        cursor.close();// 游标关闭    }    /**     * 获取记录总数     *     * @return     */    private long countData()    {        SQLiteDatabase db = databaseHelper.getReadableDatabase();        // 没有占位符参数的话,直接用null        Cursor cursor = db.rawQuery("select * from person", null);        int count = cursor.getCount();        cursor.close();        return count;    }    /**     * 分页     *     * @param offset     * @param count     */    private void getScrollData(int offset, int count)    {        ArrayList<Person> persons = new ArrayList<Person>();        SQLiteDatabase db = databaseHelper.getReadableDatabase();        // offset开始索引        // count 记录条数        Cursor cursor = db.rawQuery("select personid,name,age from person limit ?,?", new String[]        {                String.valueOf(offset), String.valueOf(count)        });        while (cursor.moveToNext())        {            Person person = new Person();            person.setId(cursor.getInt(cursor.getColumnIndex("personid")));            person.setName(cursor.getString(cursor.getColumnIndex("name")));            person.setAge(cursor.getInt(cursor.getColumnIndex("age")));            persons.add(person);            Log.i("SQLiteTestActivity", "name:" + person.getName() + "\nage:" + person.getAge());        }        System.out.println("大小================" + persons.size());        cursor.close();    }    private void other()    {        Intent intent = new Intent(SQLiteTestActivity.this, OtherActivity.class);        startActivity(intent);    }}

OtherActivity.java(第二种方法)

public class OtherActivity extends Activity implements OnClickListener{    private Button addBtn, addListBtn, delBtn, updateBtn, queryBtn, countBtn, pagingBtn;    private TextView text;    private DatabaseHelper databaseHelper;    private ArrayList<Person> personList;    @Override    public void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.other);        init();    }    private void init()    {        addBtn = (Button) findViewById(R.id.add);        addListBtn = (Button) findViewById(R.id.addList);        delBtn = (Button) findViewById(R.id.delete);        updateBtn = (Button) findViewById(R.id.update);        queryBtn = (Button) findViewById(R.id.query);        countBtn = (Button) findViewById(R.id.count);        pagingBtn = (Button) findViewById(R.id.paging);        // 设置监听        addBtn.setOnClickListener(this);        addListBtn.setOnClickListener(this);        delBtn.setOnClickListener(this);        updateBtn.setOnClickListener(this);        queryBtn.setOnClickListener(this);        countBtn.setOnClickListener(this);        pagingBtn.setOnClickListener(this);        text = (TextView) findViewById(R.id.text);        databaseHelper = new DatabaseHelper(this);    }    @Override    public void onClick(View v)    {        /**         * 添加对象         */        if (v.equals(addBtn))        {            Person person = new Person();            person.setName("Eric");            person.setAge(3);            addData(person);        }        /**         * 添加对象集合         */        if (v.equals(addListBtn))        {            personList = new ArrayList<Person>();            Person person = new Person();            person.setName("Tom");            person.setAge(2);            personList.add(person);            Person person1 = new Person();            person1.setName("Jack");            person1.setAge(3);            personList.add(person1);            Person person2 = new Person();            person2.setName("Harvey");            person2.setAge(6);            personList.add(person2);            addData(personList);        }        /**         * 删除数据         */        if (v.equals(delBtn))        {            deleteData(1);        }        /**         * 更新数据         */        if (v.equals(updateBtn))        {            Person person = new Person();            person.setId(3);            person.setName("Bob");            person.setAge(0);            updateData(person);        }        /**         * 查询数据         */        if (v.equals(queryBtn))        {            queryData(3);        }        /**         * 数据总数         */        if (v.equals(countBtn))        {            System.out.println("查询个数=====" + countData());        }        /**         * 分页         */        if (v.equals(pagingBtn))        {            getScrollData(0, 3);        }    }    /**     * 添加数据     */    private void addData(Person person)    {        SQLiteDatabase db = databaseHelper.getWritableDatabase();// 创建或者打开一个可写数据库        ContentValues contentValues = new ContentValues();        contentValues.put("name", person.getName());        contentValues.put("age", person.getAge());        db.insert("person", null, contentValues);    }    /**     * 添加集合数据     *     * @param personList     */    private void addData(ArrayList<Person> personList)    {        SQLiteDatabase db = databaseHelper.getWritableDatabase();// 创建或者打开一个可写数据库        db.beginTransaction(); // 开始事务        try        {            for (Person person : personList)            {                ContentValues contentValues = new ContentValues();                contentValues.put("name", person.getName());                contentValues.put("age", person.getAge());                db.insert("person", null, contentValues);                Log.i("SQLiteTestActivity", "name:" + person.getName() + "\nage:" + person.getAge());            }            db.setTransactionSuccessful(); // 设置事务成功完成        }        finally        {            db.endTransaction(); // 结束事务        }    }    /**     * 删除数据     *     * @param id     */    private void deleteData(Integer id)    {        SQLiteDatabase db = databaseHelper.getWritableDatabase();// 创建或者打开一个可写数据库        db.delete("person", "personid=?", new String[]        {            String.valueOf(id)        });    }    /**     * 更新数据     */    private void updateData(Person person)    {        ContentValues contentValues = new ContentValues();        contentValues.put("name", person.getName());        contentValues.put("age", person.getAge());        SQLiteDatabase db = databaseHelper.getWritableDatabase();        /**         * 第一个参数表示表名 /第二个参数表示更新的数据/第三个参数表示SQL语句的中条件部分的语句 /第四个参数占位符的值         */        db.update("person", contentValues, "personid=?", new String[]        {            String.valueOf(person.getId())        });    }    /**     * 查询数据     */    private void queryData(Integer id)    {        SQLiteDatabase db = databaseHelper.getReadableDatabase();// 创建或者打开一个查询数据库        /**         * 第一个参数表示表名 /第二个参数表示查找需要返回的字段/第三个参数表示SQL语句的中条件部分的语句         * /第四个参数占位符的值/第五个参数表示分组         * 可设为null/第六个参数表示SQL语句中的having,可设为null/第七个参数表示结果的排序,可设为null         */        Cursor cursor = db.query("person", new String[]        {                "personid", "name", "age"        }, "personid=?", new String[]        {            String.valueOf(id)        }, null, null, null);        // 迭代记录集        if (cursor.moveToNext())        {            Person person = new Person();            person.setId(cursor.getInt(cursor.getColumnIndex("personid")));            person.setName(cursor.getString(cursor.getColumnIndex("name")));            person.setAge(cursor.getInt(cursor.getColumnIndex("age"))); // 将查到的字段,放入person            System.out.println(person.toString());            text.setText(person.toString());        }        cursor.close();// 游标关闭    }    /**     * 获取记录总数     *     * @return     */    private long countData()    {        SQLiteDatabase db = databaseHelper.getReadableDatabase();        Cursor cursor = db.query("person", new String[]        {            "*"        }, null, null, null, null, null);        int count = cursor.getCount();        cursor.close();// 游标关闭        return count;    }    /**     * 分页     *     * @param offset     * @param count     */    private void getScrollData(int offset, int count)    {        ArrayList<Person> persons = new ArrayList<Person>();        SQLiteDatabase db = databaseHelper.getReadableDatabase();        Cursor cursor = db.query("person", new String[]        {                "personid", "name", "age"        }, null, null, null, null, null, offset + "," + count);        while (cursor.moveToNext())        {            Person person = new Person();            person.setId(cursor.getInt(cursor.getColumnIndex("personid")));            person.setName(cursor.getString(cursor.getColumnIndex("name")));            person.setAge(cursor.getInt(cursor.getColumnIndex("age")));            persons.add(person);            Log.i("OtherActivity", "name:" + person.getName() + "\nage:" + person.getAge());        }        System.out.println("大小================" + persons.size());        cursor.close();    }}
0 0
原创粉丝点击