欢迎投稿

今日深度:

Android Sqlite数据库常用操作,androidsqlite

Android Sqlite数据库常用操作,androidsqlite


很久前也写过一篇Android数据库操作相关内容。在正式项目中,我们通常会使用数据库开源框架如GreenDao来对数据库进行操作。
感觉很久没有直接使用Sql语句了,这几天有时间,就温习了下相关知识。
SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统.是开源的,高效率的,可嵌入且程序驱动的数据库。
使用起来非常方便,因为其API简单易用,代码量少。
1,数据类型有:
1).  NULL,值是NULL
2).  INTEGER,值是有符号整形,根据值的大小以1,2,3,4,6或8字节存放
3).  REAL,值是浮点型值,以8字节IEEE浮点数存放
4).  TEXT,值是文本字符串,使用数据库编码(UTF-8,UTF-16BE或者UTF-16LE)存放
5).  BLOB,只是一个数据块,完全按照输入存放(即没有准换)
实际也支持我们觉的Integer,varchar,time,double等类型。
在使用数据库时,我们通常要使用到的sql语句有:
1,创建表
create table 表名(字段名称 数据类型 约束,字段名称 数据类型 约束......)
例如创建一个学生表student:
create table student(_id Integer primary key,name varchar(10) not null,age Integer,scroe float)
2,删除表
drop table 表名
例如删除刚刚创建的student表:
drop table student
3,表中添加(插入数据)
insert into 表名(字段1,字段2...)values (值1,值2...)
或者:
insert into 表名 values(值1,值2...值n) 这种方式添加数据要求后面的值与数据表中字段一一对应且不能空缺字段
例如给student表中添加一条数据:
insert into student (_id,name,age,scroe) values(1,'张三',13,85.6)
4,表中删除数据
delete from 表名 where 删除的条件
比如删除student表中姓名为张三的数据:
delete from student where name="张三"
5,修改表中的数据
update 表名 set 字段=新值 where 修改的条件
例如,修改student表中张三的成绩为90update student set score=90 where _id=1
6,查询表中的数据
1,查找全部数据
select * from 表名
例如查的student表中所有数据:
select * from student
2,查找指定数据:
select 字段名 from 表名 where 查询条件 group by 分组字段 having 筛选条件 order by 排序字段
例如查询学生表student中姓名为张三的成绩:
select scroe from student where name='张三'

简单例子:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button db_create;
    private Button table_insert;
    private Button table_query;
    private Button table_delete;
    private Button table_update;
    private TextView show_tv;
    //判断是否已经创建数据库
    private boolean isCreateDb = false;
    private DBManager mDbManager;
    private MyDBHelper mDbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDbManager = DBManager.getInstance(this);
        //执行这句代码就可以创建数据库及表信息
        mDbHelper = new MyDBHelper(this);
        initViews();
    }

    /**
     * @param
     * @description 初始化UI及监听事件
     * @author ldm
     * @time 2016/11/10 9:47
     */
    private void initViews() {
        this.db_create = (Button) findViewById(R.id.db_create);
        this.table_insert = (Button) findViewById(R.id.table_insert);
        this.table_query = (Button) findViewById(R.id.table_query);
        this.table_delete = (Button) findViewById(R.id.table_delete);
        this.table_update = (Button) findViewById(R.id.table_update);
        this.show_tv = (TextView) findViewById(R.id.show_tv);
        this.db_create.setOnClickListener(this);
        this.table_insert.setOnClickListener(this);
        this.table_query.setOnClickListener(this);
        this.table_delete.setOnClickListener(this);
        this.table_update.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.db_create://创建数据库(表)
                //调用mDbManager.getDBHelper(),
                if (mDbHelper == null) {
                    mDbHelper = new MyDBHelper(this);
                }
                isCreateDb = true;
                //每次操作后,查询数据库显示结果
                queryAndShow();
                break;
            case R.id.table_insert://表中插入数据
                if (!isCreateDb) {
                    Toast.makeText(this, "请先点击按钮创建数据库相关信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                //先插入6条数据
                String sql0 = "insert into " + MyDBHelper.T_NAME + " values(1,'赵一',14,99)";
                String sql4 = "insert into " + MyDBHelper.T_NAME + " values(2,'吴二',15,67.5)";
                String sql = "insert into " + MyDBHelper.T_NAME + " values(3,'李四',14,59)";
                String sql1 = "insert into " + MyDBHelper.T_NAME + " values(4,'王五',15,80)";
                String sql2 = "insert into " + MyDBHelper.T_NAME + " values(5,'陈六',16,77.5)";
                String sql3 = "insert into " + MyDBHelper.T_NAME + " values(6,'刘大',15,83.4)";
                mDbManager.execSql(mDbHelper.getWritableDatabase(), sql0);
                mDbManager.execSql(mDbHelper.getWritableDatabase(), sql4);
                mDbManager.execSql(mDbHelper.getWritableDatabase(), sql);
                mDbManager.execSql(mDbHelper.getWritableDatabase(), sql1);
                mDbManager.execSql(mDbHelper.getWritableDatabase(), sql2);
                mDbManager.execSql(mDbHelper.getWritableDatabase(), sql3);
                //每次操作后,查询数据库显示结果
                queryAndShow();
                break;
            case R.id.table_query://查询表中数据
                if (!isCreateDb) {
                    Toast.makeText(this, "请先点击按钮创建数据库相关信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                //每次操作后,查询数据库显示结果
                queryAndShow();
                break;
            case R.id.table_delete://删除表中数据
                if (!isCreateDb) {
                    Toast.makeText(this, "请先点击按钮创建数据库相关信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                String delSql = "delete from " + MyDBHelper.T_NAME + " where " + MyDBHelper.TABLE_ID + "=3";
                mDbManager.execSql(mDbHelper.getWritableDatabase(), delSql);
                //每次操作后,查询数据库显示结果
                queryAndShow();
                break;
            case R.id.table_update://修改表中数据
                if (!isCreateDb) {
                    Toast.makeText(this, "请先点击按钮创建数据库相关信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                String updSql = "update " + MyDBHelper.T_NAME + " set " + MyDBHelper.TABLE_NAME + "='李九'" + " where " + MyDBHelper.TABLE_ID + "=5";
                mDbManager.execSql(mDbHelper.getWritableDatabase(), updSql);
                //每次操作后,查询数据库显示结果
                queryAndShow();
                break;
        }
    }

    /**
     * @param
     * @description 查询数据并显示数据内容
     * @author ldm
     * @time 2016/11/10 10:18
     */
    private void queryAndShow() {
        String sql = "select * from " + MyDBHelper.T_NAME;
        StringBuffer sb = new StringBuffer();
        Cursor cursor = mDbHelper.getWritableDatabase().rawQuery(sql, null);
        while (cursor.moveToNext()) {
            sb.append("_id=").append(cursor.getString(cursor.getColumnIndex(MyDBHelper.TABLE_ID))).append(" ")
                    .append("name=").append(cursor.getString(cursor.getColumnIndex(MyDBHelper.TABLE_NAME))).append(" ")
                    .append("age=").append(cursor.getInt(cursor.getColumnIndex(MyDBHelper.TABLE_AGE))).append(" ")
                    .append("score=").append(cursor.getInt(cursor.getColumnIndex(MyDBHelper.TABLE_SCORE)))
                    .append("\n");
        }
        show_tv.setText("查询结果是:\n" + sb.toString());
    }
/*--除了用基础的Sql语句操作数据外,还可以直接使用Android提示的数据库操作方法,网上资料很多,就不记录啦---**/
}

数据库操作类:SQLiteOpenHelper

public class MyDBHelper extends SQLiteOpenHelper {
    private final static String DB_NAME = "test";
    private final static int DB_VERSION = 1;
    public final static String T_NAME = "student";
    public final static String TABLE_ID = "_id";
    public final static String TABLE_NAME = "name";
    public final static String TABLE_AGE = "age";
    public final static String TABLE_SCORE = "score";

    public MyDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    //定义参数简单地构造方法
    public MyDBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    //数据库创建时调用
    @Override
    public void onCreate(SQLiteDatabase db) {
        //如果写有创建表的Sql语句时,就会在创建数据的时候创建对应的表格
        String sql = "create table " + T_NAME + "("
                + TABLE_ID + " Integer primary key,"
                + TABLE_NAME + " varchar(10),"
                + TABLE_AGE + " Integer,"
                + TABLE_SCORE + " float"
                + ")";
        //执行创建表格语句
        db.execSQL(sql);
    }

    //数据库版本发生更新时调用
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //更新数据库
    }

    //打开数据库时调用
    @Override
    public void onOpen(SQLiteDatabase db) {
        //如果数据库已经存在,则再次运行不执行onCreate()方法,而是执行onOpen()打开数据库
        super.onOpen(db);
    }
}

实际 项目中应该把数据库操作方法统一封装一下:

public class DBManager {
    private static DBManager dbManager;
    private Context context;

    private DBManager(Context context) {
        this.context = context;
    }

    public static DBManager getInstance(Context context) {
        if (null == dbManager) {
            dbManager = new DBManager(context);
        }
        return dbManager;
    }

    /**
     * @param
     * @description 通过执行sql语句来操作数据库
     * @author ldm
     * @time 2016/11/10 9:25
     */
    public void execSql(SQLiteDatabase db, String sql) {
        if (null != db && !TextUtils.isEmpty(sql)) {
            db.execSQL(sql);
        }
        db.close();
    }
}

主界面布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.ldm.androiddb.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sqlite数据库操作" />

    <Button
        android:id="@+id/db_create"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="创建数据库"
        android:textSize="16sp" />

    <Button
        android:id="@+id/table_insert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="表中插入数据"
        android:textSize="16sp" />

    <Button
        android:id="@+id/table_query"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="查询表中数据"
        android:textSize="16sp" />

    <Button
        android:id="@+id/table_delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="删除表中数据"
        android:textSize="16sp" />

    <Button
        android:id="@+id/table_update"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="修改表中数据"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/show_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textSize="15sp"
        android:textColor="@android:color/holo_blue_bright"/>
</LinearLayout>

添加权限 :

 <!-- 在SDCard中创建与删除文件权限 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <!-- 往SDCard写入数据权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

效果贴图:

www.htsjk.Com true http://www.htsjk.com/SQLite/35855.html NewsArticle Android Sqlite数据库常用操作,androidsqlite 很久前也写过一篇Android数据库操作相关内容。在正式项目中,我们通常会使用数据库开源框架如GreenDao来对数据库进行操作。感觉很久没有直接使...
相关文章
    暂无相关文章
评论暂时关闭