当前位置: 移动技术网 > IT编程>移动开发>Android > Android SQLite详解及示例代码

Android SQLite详解及示例代码

2019年07月24日  | 移动技术网IT编程  | 我要评论

911,王亚楠老婆,纸牌屋第三季中文字幕

在android中使用sqlite数据库的入门指南,打算分下面几部分与大家一起分享,

1、什么是sqlite

2、android中使用sqlite

一、什么是sqlite

sqlite是一款开源的、轻量级的、嵌入式的、关系型数据库。它在2000年由d. richard hipp发布,可以支援java、net、php、ruby、python、perl、c等几乎所有的现代编程语言,支持windows、linux、unix、mac os、android、ios等几乎所有的主流操作系统平台。

sqlite被广泛应用的在苹果、adobe、google的各项产品。如果非要举一个你身边应用sqlite的例子的话,如果你的机器中装的有迅雷,请打开迅雷安装目录,搜索一下sqlite3.dll,是不是找到了它的身影? 如果你装的有金山词霸,那么打开他的安装目录也会看到sqlite.dll的存在。是的,sqlite早就广泛的应用在我们接触的各种产品中了,当然我们今天学习它,是因为在android开发中,android推荐的数据库,也是内置了完整支持的数据库就是sqlite。

sqlite的特性:

1. acid事务
2. 零配置 – 无需安装和管理配置
3. 储存在单一磁盘文件中的一个完整的数据库
4. 数据库文件可以在不同字节顺序的机器间自由的共享
5. 支持数据库大小至2tb
6. 足够小, 大致3万行c代码, 250k
7. 比一些流行的数据库在大部分普通数据库操作要快
8. 简单, 轻松的api
9. 包含tcl绑定, 同时通过wrapper支持其他语言的绑定
10. 良好注释的源代码, 并且有着90%以上的测试覆盖率
11. 独立: 没有额外依赖
12. source完全的open, 你可以用于任何用途, 包括出售它
13. 支持多种开发语言,c, php, perl, java, asp.net,python

推荐的sqlite客户端管理工具,火狐插件 sqlite manger

二、android中使用sqlite

我们还是通过一个例子来学习,相关讲解都写在代码注释里。

1、新建一个项目lesson15_hellosqlite,activity起名叫mainhellosqlite.java

2、编写用户界面 res/layout/main.xml,准备增(insert)删(delete)改(update)查(select)四个按钮,准备一个下拉列表spinner,显示表中的数据。

<?xml version="1.0" encoding="utf-8"?>
<linearlayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">

    <textview android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/textview01" android:text="sqlite基本操作">
    </textview>

    <button android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/button01" android:text="增 | insert" android:minwidth="200dp"></button>

    <button android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/button02" android:text="删 | delete" android:minwidth="200dp"></button>

    <button android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/button03" android:text="改 | update" android:minwidth="200dp"></button>

    <button android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/button04" android:text="查 | select" android:minwidth="200dp"></button>

    <spinner android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_margintop="5dp" android:id="@+id/spinner01" android:minwidth="200dp">
    </spinner>

    <textview android:layout_height="wrap_content" android:layout_width="wrap_content" android:textsize="20sp" android:layout_margintop="5dp" android:id="@+id/textview02"></textview>
</linearlayout>

3、在mainhelosqlite.java的同目录中新建一个数据库操作辅助类 dbhelper.java,内容如下:

package android.basic.lesson15;

import android.content.context;
import android.database.sqlite.sqlitedatabase;
import android.database.sqlite.sqlitedatabase.cursorfactory;
import android.database.sqlite.sqliteopenhelper;

public class dbhelper extends sqliteopenhelper {

    public dbhelper(context context, string name, cursorfactory factory,
            int version) {
        super(context, name, factory, version);
    }

    //辅助类建立时运行该方法
    @override
    public void oncreate(sqlitedatabase db) {

        string sql = "create table pic (_id integer primary key autoincrement not null , filename varchar, description varchar)";
        db.execsql(sql);
    }

    @override
    public void onupgrade(sqlitedatabase db, int oldversion, int newversion) {
    }

}

4、mainhellosqlite.java的内容如下:

package android.basic.lesson15;

import android.app.activity;
import android.content.contentvalues;
import android.database.cursor;
import android.database.sqlite.sqlitedatabase;
import android.os.bundle;
import android.view.view;
import android.view.view.onclicklistener;
import android.widget.adapterview;
import android.widget.adapterview.onitemselectedlistener;
import android.widget.button;
import android.widget.simplecursoradapter;
import android.widget.spinner;
import android.widget.textview;
import android.widget.toast;

public class mainhellosqlite extends activity {

    //sqlitedatabase对象
    sqlitedatabase db;
    //数据库名
    public string db_name = "gallery.sqlite";
    //表名
    public string table_name = "pic";

    //辅助类名
    final dbhelper helper = new dbhelper(this, db_name, null, 1);

    /** called when the activity is first created. */
    @override
    public void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.main);

        //ui组件
        button b1 = (button) findviewbyid(r.id.button01);
        button b2 = (button) findviewbyid(r.id.button02);
        button b3 = (button) findviewbyid(r.id.button03);
        button b4 = (button) findviewbyid(r.id.button04);

        //从辅助类获得数据库对象
        db = helper.getwritabledatabase();

        //初始化数据
        initdatabase(db);
        //更新下拉列表中的数据
        updatespinner();

        //定义按钮点击监听器
        onclicklistener ocl = new onclicklistener() {

            @override
            public void onclick(view v) {

                //contentvalues对象
                contentvalues cv = new contentvalues();
                switch (v.getid()) {

                //添加按钮
                case r.id.button01:

                    cv.put("filename", "pic5.jpg");
                    cv.put("description", "图片5");
                    //添加方法
                    long long1 = db.insert("pic", "", cv);
                    //添加成功后返回行号,失败后返回-1
                    if (long1 == -1) {
                        toast.maketext(mainhellosqlite.this,
                                "id是" + long1 + "的图片添加失败!", toast.length_short)
                                .show();
                    } else {
                        toast.maketext(mainhellosqlite.this,
                                "id是" + long1 + "的图片添加成功!", toast.length_short)
                                .show();
                    }
                    //更新下拉列表
                    updatespinner();
                    break;

                //删除描述是'图片5'的数据行
                case r.id.button02:
                    //删除方法
                    long long2 = db.delete("pic", "description='图片5'", null);
                    //删除失败返回0,成功则返回删除的条数
                    toast.maketext(mainhellosqlite.this, "删除了" + long2 + "条记录",
                            toast.length_short).show();
                    //更新下拉列表
                    updatespinner();
                    break;

                //更新文件名是'pic5.jpg'的数据行
                case r.id.button03:

                    cv.put("filename", "pic0.jpg");
                    cv.put("description", "图片0");
                    //更新方法
                    int long3 = db.update("pic", cv, "filename='pic5.jpg'", null);
                    //删除失败返回0,成功则返回删除的条数
                    toast.maketext(mainhellosqlite.this, "更新了" + long3 + "条记录",
                            toast.length_short).show();
                    //更新下拉列表
                    updatespinner();
                    break;

                //查询当前所有数据
                case r.id.button04:
                    cursor c = db.query("pic", null, null, null, null,
                            null, null);
                    //cursor.getcount()是记录条数
                    toast.maketext(mainhellosqlite.this,
                            "当前共有" + c.getcount() + "条记录,下面一一显示:",
                            toast.length_short).show();
                    //循环显示
                    for(c.movetofirst();!c.isafterlast();c.movetonext()){
                        toast.maketext(mainhellosqlite.this,
                                "第"+ c.getint(0) +"条数据,文件名是" + c.getstring(1) + ",描述是"+c.getstring(2),
                                toast.length_short).show();
                    }
                    //更新下拉列表
                    updatespinner();
                    break;
                }
            }
        };

        //给按钮绑定监听器
        b1.setonclicklistener(ocl);
        b2.setonclicklistener(ocl);
        b3.setonclicklistener(ocl);
        b4.setonclicklistener(ocl);

    }

    //初始化表
    public void initdatabase(sqlitedatabase db) {
        contentvalues cv = new contentvalues();

        cv.put("filename", "pic1.jpg");
        cv.put("description", "图片1");
        db.insert(table_name, "", cv);

        cv.put("filename", "pic2.jpg");
        cv.put("description", "图片2");
        db.insert(table_name, "", cv);

        cv.put("filename", "pic3.jpg");
        cv.put("description", "图片3");
        db.insert(table_name, "", cv);

        cv.put("filename", "pic4.jpg");
        cv.put("description", "图片4");
        db.insert(table_name, "", cv);

    }

    //更新下拉列表
    public void updatespinner() {

        //定义ui组件
        final textview tv = (textview) findviewbyid(r.id.textview02);
        spinner s = (spinner) findviewbyid(r.id.spinner01);

        //从数据库中获取数据放入游标cursor对象
        final cursor cursor = db.query("pic", null, null, null, null, null,
                null);

        //创建简单游标匹配器
        simplecursoradapter adapter = new simplecursoradapter(this,
                android.r.layout.simple_spinner_item, cursor, new string[] {
                        "filename", "description" }, new int[] {
                        android.r.id.text1, android.r.id.text2 });
        adapter.setdropdownviewresource(android.r.layout.simple_spinner_dropdown_item);

        //给下拉列表设置匹配器
        s.setadapter(adapter);

        //定义子元素选择监听器
        onitemselectedlistener oisl = new onitemselectedlistener() {

            @override
            public void onitemselected(adapterview<?> parent, view view,
                    int position, long id) {
                cursor.movetoposition(position);
                tv.settext("当前pic的描述为:" + cursor.getstring(2));
            }

            @override
            public void onnothingselected(adapterview<?> parent) {
            }
        };

        //给下拉列表绑定子元素选择监听器
        s.setonitemselectedlistener(oisl);
    }

    //窗口销毁时删除表中数据
    @override
    public void ondestroy() {
        super.ondestroy();
        db.delete(table_name, null, null);
        updatespinner();
    }
}

5、运行程序,查看结果:

本例使用的是sqlitedatabase已经封装好的insert,delete,update,query方法,感兴趣的同学可以用sqlitedatabase的execsql()方法和rawquery()方法来实现。好本讲就到这里。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网