美文网首页
Android 常用数据库SQLite基本使用

Android 常用数据库SQLite基本使用

作者: 我弟是个程序员 | 来源:发表于2017-07-22 20:10 被阅读0次

    话不多说,就是数据库的存储,将一些可以不用劳烦服务器存储的数据存储在本地,像购物车啊,断点续传下载啊,可能会记录一些数据信息,就会使用到。下面来看看SQLite基本的用法吧。

    首先当然是创建数据库和表信息,新建DBHelper.java文件:

    package com.dingfang.org.sqlitedemo.db;
    
    import android.content.Context;
    import android.database.DatabaseErrorHandler;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    
    public class DBHelper extends SQLiteOpenHelper {
    
        /**
         * 数据库名称
         * 数据库的创建,不需要我们认为控制,提供数据库名称和版本号就行了
         */
        private static final String DB_NAME = "download.db";
        /**
         * 数据库版本号
         */
        private static final int VERSION = 1;
        /**
         * 创建表 thread_info
         */
        private static final String SQL_CREATE = "create table thread_info(_id integer primary key autoincrement," +
                "thread_id integer, url text, start integer, end integer, finished integer)";
        /**
         *删除表 thread_info
         */
        private static final String SQL_DROP = "drop table if exists thread_info";
    
        public DBHelper(Context context) {
            super(context, DB_NAME, null, VERSION);
        }
    
        public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }
    
        public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
            super(context, name, factory, version, errorHandler);
        }
    
        /**
         * 创建表操作
         * @param sqLiteDatabase
         */
        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {
            sqLiteDatabase.execSQL(SQL_CREATE);
        }
    
        /**
         * 当前版本号和最新版本号进行比较,如果大于的话,就执行升级操作onUpgrade方法,否则就执行降级onDowngrade方法,
         * 不过降级方法实现很简单,一般是不允许降级操作的,因为会抛异常
         * @param sqLiteDatabase
         * @param oldVersion
         * @param newVersion
         */
        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
            //本人认为,如果数据更新操作,不想删除表的话,是不是直接写一个添加字段的sql语句执行就行了。
            sqLiteDatabase.execSQL(SQL_DROP);
            sqLiteDatabase.execSQL(SQL_CREATE);
        }
    }
    
    

    注释都很清楚了,上面创建了数据库,其名称是download.db,创建数据库的这个过程,程序员根本就不用关心就,我们的心思应该放在创建表上。上面看创建了表thread_info,下面我们来为表写一个实体类,为的是存储表数据时有个容器盛放,是吧。新建一个ThreadInfo实体类:

    package com.dingfang.org.sqlitedemo.entity;
    
    /**
     * 线程信息
     */
    public class ThreadInfo {
        private int id;
        private String url;
        private int start;
        private int end;
        private int finished;
    
        public ThreadInfo() {
        }
    
        /**
         * @param id
         * @param url  下载信息
         * @param start  下载的位置
         * @param end   下载目标位置
         * @param finished  已经下载到订单位置
         */
        public ThreadInfo(int id, String url, int start, int end, int finished) {
            this.id = id;
            this.url = url;
            this.start = start;
            this.end = end;
            this.finished = finished;
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getUrl() {
            return url;
        }
    
        public void setUrl(String url) {
            this.url = url;
        }
    
        public int getStart() {
            return start;
        }
    
        public void setStart(int start) {
            this.start = start;
        }
    
        public int getEnd() {
            return end;
        }
    
        public void setEnd(int end) {
            this.end = end;
        }
    
        public int getFinished() {
            return finished;
        }
    
        public void setFinished(int finished) {
            this.finished = finished;
        }
    
        @Override
        public String toString() {
            return "ThreadInfo [id=" + id + ", url=" + url + ", start=" + start
                    + ", end=" + end + ", finished=" + finished + "]";
        }
    
    }
    
    

    再接着是不是该对数据库新建的表进行增删改相关的操作了呢,新建一个接口ThreadDAO如下:

    package com.dingfang.org.sqlitedemo.db.dao;
    
    
    import com.dingfang.org.sqlitedemo.entity.ThreadInfo;
    
    import java.util.List;
    
    /**
     * ThreadInfo 数据访问接口
     */
    public interface ThreadDAO
    {
        /**
         * 插入线程信息
         */
        public void insertThread(ThreadInfo threadInfo);
        /**
         * 删除线程信息
         */
        public void deleteThread(String url, int thread_id);
        /**
         * 更新线程下载进度
         */
        public void updateThread(String url, int thread_id, int finished);
        /**
         * 查询文件的线程信息
         */
        public List<ThreadInfo> getThreads(String url);
        /**
         * 线程信息是否存在
         */
        public boolean isExists(String url, int thread_id);
    }
    
    

    然后对上面的接口进行实现,新建ThreadDAOImpl类:

    package com.dingfang.org.sqlitedemo.db.dao;
    
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    
    import com.dingfang.org.sqlitedemo.db.DBHelper;
    import com.dingfang.org.sqlitedemo.entity.ThreadInfo;
    
    import java.util.ArrayList;
    import java.util.List;
    
    
    /**
     * 数据访问接口实现
     */
    public class ThreadDAOImpl implements ThreadDAO {
        private DBHelper mHelper = null;
    
        public ThreadDAOImpl(Context context) {
            mHelper = new DBHelper(context);
        }
    
    
        /**
         * 增
         * @param threadInfo
         */
        @Override
        public void insertThread(ThreadInfo threadInfo) {
            SQLiteDatabase db = mHelper.getWritableDatabase();
            db.execSQL("insert into thread_info(thread_id,url,start,end,finished) values(?,?,?,?,?)",
                    new Object[]{threadInfo.getId(), threadInfo.getUrl(),
                            threadInfo.getStart(), threadInfo.getEnd(), threadInfo.getFinished()});
            db.close();
        }
    
        /**
         * 删
         * @param url
         * @param thread_id
         */
        @Override
        public void deleteThread(String url, int thread_id) {
            SQLiteDatabase db = mHelper.getWritableDatabase();
            db.execSQL("delete from thread_info where url = ? and thread_id = ?",
                    new Object[]{url, thread_id});
            db.close();
        }
    
        /**
         * 改
         * @param url
         * @param thread_id
         * @param finished
         */
        @Override
        public void updateThread(String url, int thread_id, int finished) {
            SQLiteDatabase db = mHelper.getWritableDatabase();
            db.execSQL("update thread_info set finished = ? where url = ? and thread_id = ?",
                    new Object[]{finished, url, thread_id});
            db.close();
        }
    
        /**
         * 查
         * @param url
         * @return
         */
        @Override
        public List<ThreadInfo> getThreads(String url) {
            List<ThreadInfo> list = new ArrayList<ThreadInfo>();
    
            SQLiteDatabase db = mHelper.getWritableDatabase();
            Cursor cursor = db.rawQuery("select * from thread_info where url = ?", new String[]{url});
            while (cursor.moveToNext()) {
                ThreadInfo threadInfo = new ThreadInfo();
                threadInfo.setId(cursor.getInt(cursor.getColumnIndex("thread_id")));
                threadInfo.setUrl(cursor.getString(cursor.getColumnIndex("url")));
                threadInfo.setStart(cursor.getInt(cursor.getColumnIndex("start")));
                threadInfo.setEnd(cursor.getInt(cursor.getColumnIndex("end")));
                threadInfo.setFinished(cursor.getInt(cursor.getColumnIndex("finished")));
                list.add(threadInfo);
            }
            cursor.close();
            db.close();
            return list;
        }
    
        /**
         * 判断是否存在
         * @param url
         * @param thread_id
         * @return
         */
        @Override
        public boolean isExists(String url, int thread_id) {
            SQLiteDatabase db = mHelper.getWritableDatabase();
            Cursor cursor = db.rawQuery("select * from thread_info where url = ? and thread_id = ?", new String[]{url, thread_id + ""});
            boolean exists = cursor.moveToNext();
            cursor.close();
            db.close();
            return exists;
        }
    }
    
    

    到此,所有的数据库创建,表创建,以及数据库表的访问操作就完成了。下面来看一下使用 。
    新建一个MainActivity:

    package com.dingfang.org.sqlitedemo;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.TextView;
    
    import com.dingfang.org.sqlitedemo.db.dao.ThreadDAO;
    import com.dingfang.org.sqlitedemo.db.dao.ThreadDAOImpl;
    import com.dingfang.org.sqlitedemo.entity.ThreadInfo;
    
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity {
        private TextView textView;
    
        ThreadDAO dao;//数据库操作类
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            initView();
        }
    
        private void initView() {
    
            textView = (TextView) findViewById(R.id.content);
            dao = new ThreadDAOImpl(this);
        }
    
        public void onBtnClicked(View v) {
            switch (v.getId()) {
                case R.id.save:
                    onSaveClicked();
                    break;
                case R.id.fetch:
                    onFetchClicked();
                    break;
    
            }
        }
    
        public void onSaveClicked() {
            ThreadInfo info = new ThreadInfo(2, "http:www.ttreader.com", 0, 1024 * 10, 1234);
            dao.insertThread(info);
        }
        public void onFetchClicked() {
            List<ThreadInfo> infos = dao.getThreads("http:www.ttreader.com");
    
            String finishedStr = "";
            for (ThreadInfo item : infos) {
                finishedStr += item.getFinished();
            }
    
            textView.setText("已完成进度:" + finishedStr);
        }
    }
    
    

    activity_main.xml文件很简单,为了理解上面的代码,还是贴出来如下:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:id="@+id/content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text="Hello World!" />
    
        <Button
            android:id="@+id/save"
            android:onClick="onBtnClicked"
            android:text="存"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/fetch"
            android:onClick="onBtnClicked"
            android:text="取"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    
    </LinearLayout>
    

    都是很简单的操作,这里就不做过多解释了,可以动手试试了。

    相关文章

      网友评论

          本文标题:Android 常用数据库SQLite基本使用

          本文链接:https://www.haomeiwen.com/subject/xohykxtx.html