隐藏

SQList在android中使用

发布:2023/9/19 10:23:33作者:管理员 来源:本站 浏览次数:504

1.什么是SQList,为什么要用SQList


SQList是顺序链表,属于链表类型,轻量级数据存储,方便增、删、改、查。

1.SQLite数据库存储是安卓系统提供的存储方式之一


2.SQLite是专为嵌入式设备设计的一款轻量级数据库


3.SQLite占用资源非常低,在嵌入式设备中,只需要几百kb的内存


4.SQLite支持标准的SQL语句,遵循数据库的ACID失误


5.SQLite不需要安装,不需要用户名密码就能使用


要用SQList的原因


1.SharedPreferences是以xml形式储存数据的,只适合储存基本类型的数据


2.文件储存的内容在提取(解析)数据时,相对复杂


3.当数据量大、结构复杂时,如果使用SharedPreferences和文件储存对数据的操作将变得非常复杂,容易出错,效率低下,Android提供了SQLite数据存贮,帮助我们解决这些问题

2.如何创建数据库和数据表


SQLite 的 sqlite3 命令被用来创建新的 SQLite 数据库

语法


$sqlite3 DatabaseName.db




通常情况下,数据库名称在 RDBMS 内应该是唯一的。

实例


建一个新的数据库 <testDB.db>,SQLITE3 语句如下所示:




$sqlite3 testDB.db

SQLite version 3.7.15.2 2013-01-09 11:53:05

Enter ".help" for instructions

Enter SQL statements terminated with a ";"

sqlite>


 


上面的命令将在当前目录下创建一个文件 testDB.db。该文件将被 SQLite 引擎用作数据库。如果您已经注意到 sqlite3 命令在成功创建数据库文件之后,将提供一个 sqlite> 提示符。

一旦数据库被创建,您就可以使用 SQLite 的 .databases 命令来检查它是否在数据库列表中,如下所示:


seq  name             file

0    main             /home/sqlite/testDB.db




您可以使用 SQLite .quit 命令退出 sqlite 提示符,如下所示:


sqlite>.quit

$




dump 命令


您可以在命令提示符中使用 SQLite .dump 点命令来导出完整的数据库在一个文本文件中,如下所示:


$sqlite3 testDB.db .dump > testDB.sql




上面的命令将转换整个 testDB.db 数据库的内容到 SQLite 的语句中,并将其转储到 ASCII 文本文件 testDB.sql 中。您可以通过简单的方式从生成的 testDB.sql 恢复,如下所示:


$sqlite3 testDB.db < testDB.sql




SQLite 的 CREATE TABLE 语句用于在任何给定的数据库创建一个新表。创建基本表,涉及到命名表、定义列及每一列的数据类型。

语法


CREATE TABLE 语句的基本语法如下:


CREATE TABLE database_name.table_name(

  column1 datatype  PRIMARY KEY(one or more columns),

  column2 datatype,

  column3 datatype,

  .....

  columnN datatype,

);


  


CREATE TABLE 是告诉数据库系统创建一个新表的关键字。CREATE TABLE 语句后跟着表的唯一的名称或标识。您也可以选择指定带有 table_name 的 database_name。

实例


下面是一个实例,它创建了一个 COMPANY 表,ID 作为主键,NOT NULL 的约束表示在表中创建纪录时这些字段不能为 NULL:


sqlite> CREATE TABLE COMPANY(

  ID INT PRIMARY KEY     NOT NULL,

  NAME           TEXT    NOT NULL,

  AGE            INT     NOT NULL,

  ADDRESS        CHAR(50),

  SALARY         REAL

);


 


让我们再创建一个表,我们将在随后章节的练习中使用:


sqlite> CREATE TABLE DEPARTMENT(

  ID INT PRIMARY KEY      NOT NULL,

  DEPT           CHAR(50) NOT NULL,

  EMP_ID         INT      NOT NULL

);


 


您可以使用 SQLIte 命令中的 .tables 命令来验证表是否已成功创建,该命令用于列出附加数据库中的所有表。


sqlite>.tables

COMPANY     DEPARTMENT




在这里,可以看到我们刚创建的两张表 COMPANY、 DEPARTMENT。

您可以使用 SQLite .schema 命令得到表的完整信息,如下所示:


sqlite>.schema COMPANY

CREATE TABLE COMPANY(

  ID INT PRIMARY KEY     NOT NULL,

  NAME           TEXT    NOT NULL,

  AGE            INT     NOT NULL,

  ADDRESS        CHAR(50),

  SALARY         REAL

);


 


3.简单的增删改查的实现


布局文件:


<?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:layout_width="match_parent"

   android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context=".database.Activity.SQLiteActivity">


   <EditText

      android:id="@+id/titleText"

      android:layout_width="match_parent"

      android:layout_height="wrap_content"

      android:hint="请输入标题" />


   <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:orientation="horizontal">


        <TextView

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

           android:text="请输入要删除的数据" />


        <EditText

         android:id="@+id/deleteText"

         android:layout_width="match_parent"  

         android:layout_height="wrap_content" />

   </LinearLayout>


   <LinearLayout

      android:layout_width="match_parent"

      android:layout_height="wrap_content"

      android:orientation="horizontal">


      <TextView

          android:layout_width="wrap_content"

          android:layout_height="wrap_content"

          android:text="请输入要修改的数据" />


       <EditText

        android:id="@+id/updateText"

        android:layout_width="match_parent"    

        android:layout_height="wrap_content" />

  </LinearLayout>

    <Button

      android:id="@+id/insertData"

      android:layout_width="match_parent"

      android:layout_height="wrap_content"

      android:text="添加数据" />


  <Button

       android:id="@+id/queryData"

       android:layout_width="match_parent"

       android:layout_height="wrap_content"

       android:text="查找数据  " />


   <Button

       android:id="@+id/updateData"

       android:layout_width="match_parent"

       android:layout_height="wrap_content"

      android:text="修改数据" />

   <Button  

     android:id="@+id/deleteData"

       android:layout_width="match_parent"

       android:layout_height="wrap_content"

       android:text="删除数据" />

</LinearLayout>




Activity


package com.example.administrator.myapplication.database.Activity;


 import android.content.ContentValues;

  import android.database.Cursor;

 import android.database.sqlite.SQLiteDatabase;

 import android.os.Bundle;

  import android.support.v7.app.AppCompatActivity;

  import android.view.View;

 android.widget.Button;

 import android.widget.EditText;

import android.widget.Toast;


import com.example.administrator.myapplication.R;

import com.example.administrator.myapplication.database.MySQLiteOpenHelper;

import com.example.administrator.myapplication.util.Common;


public class SQLiteActivity extends AppCompatActivity {

    Button insertBtn;

   Button queryBtn;

    Button deleteBtn;

    Button updateBtn;

   EditText titleET;

   EditText deleteET;

    EditText updateET;

    String TitleReceiver;

    String deleteReceiver;

    String updateReceiver;


    @Override

   protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_sqlite);

       titleET = (EditText) findViewById(R.id.titleText);

       deleteET = (EditText) findViewById(R.id.deleteText);

       updateET = (EditText) findViewById(R.id.updateText);

        insertBtn = (Button) findViewById(R.id.insertData);

      insertBtn.setOnClickListener(new View.OnClickListener() {

            @Override

           public void onClick(View v) {

               insertData();

           }

       });

       queryBtn = (Button) findViewById(R.id.queryData);

        queryBtn.setOnClickListener(new View.OnClickListener() {

             @Override

           public void onClick(View v) {

               queryData();

           }

       });

        deleteBtn = (Button) findViewById(R.id.deleteData);

       deleteBtn.setOnClickListener(new View.OnClickListener() {

            @Override

           public void onClick(View v) {

               deleteData();

           }

        });

       updateBtn = (Button) findViewById(R.id.updateData);

        updateBtn.setOnClickListener(new View.OnClickListener() {

            @Override            public void onClick(View v) {

               updateData();

           }

       });

   }


   //插入数据

    public void insertData(){

       TitleReceiver = titleET.getText().toString();

        //调用帮助类的构造函数,创建数据库

        MySQLiteOpenHelper mySQLiteOpenHelper = new MySQLiteOpenHelper(this);

       //调用帮助类的onCreate方法,创建表

        SQLiteDatabase sqLiteDatabase = mySQLiteOpenHelper.getWritableDatabase();

       //将保存的数据放入ContentValues中

       ContentValues contentValues = new ContentValues();

      contentValues.put(Common.NewsTable.TBL_TITLE,TitleReceiver);

       contentValues.put(Common.NewsTable.TBL_CONTENT,"内容");

       contentValues.put(Common.NewsTable.TBL_SRC,"图片");

       contentValues.put(Common.NewsTable.TBL_DATE,"日期");

        //调用insert方法,保存数据

      sqLiteDatabase.insert(Common.NewsTable.TBL_NAME,null,contentValues);

       //!!!数据库操作完成后,一定要关闭数据库

        sqLiteDatabase.close();

        Toast.makeText(getApplication(),"保存数据成功!",Toast.LENGTH_SHORT).show();

   }

   //查询数据

    public void queryData(){

       MySQLiteOpenHelper mySQLiteOpenHelper = new MySQLiteOpenHelper(this);

        SQLiteDatabase sqLiteDatabase = mySQLiteOpenHelper.getReadableDatabase();

       //调用SQLiteDatabase的Query方法,返回数据库查询的结果集

       Cursor cursor = sqLiteDatabase.query(

               Common.NewsTable.TBL_NAME,

               new String[]{Common.NewsTable.TBL_TITLE,Common.NewsTable.TBL_CONTENT,Common.NewsTable.TBL_SRC,Common.NewsTable.TBL_DATE},

              null,null,null,null,null

       );

       //!!查询对应数据的时候,一定要现获取列的索引值

      while (cursor.moveToNext()){

          int titleIndex = cursor.getColumnIndex(Common.NewsTable.TBL_TITLE);

          String title = cursor.getString(titleIndex);

         Toast.makeText(getApplication(),title,Toast.LENGTH_SHORT).show();

      }

      //数据查询完毕以后,1:关系结果集 2.关闭SQLiteDataBase

       cursor.close();

       sqLiteDatabase.close();

        Toast.makeText(getApplication(),"查询完毕!",Toast.LENGTH_SHORT).show();

    }

  //删除数据

    private void deleteData() {

       deleteReceiver = deleteET.getText().toString();

        MySQLiteOpenHelper mySQLiteOpenHelper = new MySQLiteOpenHelper(this);

        SQLiteDatabase sqLiteDatabase = mySQLiteOpenHelper.getWritableDatabase();

        sqLiteDatabase.delete(

              Common.NewsTable.TBL_NAME,

              // ?:占位符 " = ? "相当于 " = 标题 ", null

              Common.NewsTable.TBL_TITLE+ " = ?",

               new String[]{deleteReceiver}

        );

       sqLiteDatabase.close();

       Toast.makeText(getApplication(),"删除成功!",Toast.LENGTH_SHORT).show();

    }

   //修改数据

  private void updateData() {

       updateReceiver = updateET.getText().toString();

       MySQLiteOpenHelper mySQLiteOpenHelper = new MySQLiteOpenHelper(this);

        SQLiteDatabase sqLiteDatabase = mySQLiteOpenHelper.getWritableDatabase();

       ContentValues contentValues = new ContentValues();

      contentValues.put(Common.NewsTable.TBL_TITLE,"这是修改后的数据");

        sqLiteDatabase.update(

               Common.NewsTable.TBL_NAME,

               contentValues,

              mmon.NewsTable.TBL_TITLE + " = ?",

               new String[]{updateReceiver}

      );

       sqLiteDatabase.close();

        Toast.makeText(getApplication(),"修改成功!",Toast.LENGTH_SHORT).show();

   }

}


 


MySQListOPENHelper 创建数据库 创建表


package com.example.administrator.myapplication.database;


import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;


import com.example.administrator.myapplication.util.Common;


/**

 * Created by Administrator on 2016-9-19.

 */


//帮助类继承SQLiteOpenHelper,方法:构造函数,创建数据库,创建表,更新表

public class MySQLiteOpenHelper extends SQLiteOpenHelper {

   private static final String DB_Name = "new.db"; //数据库后缀为db,常量用大写

   private static final int VERSION = 1; //数据库版本号

   //上下文,数据库名字,factory默认null,版本号

    /*public MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {

       super(context, DB_Name, factory, VERSION);

    }*/

   //实现了数据库的创建,factory默认null,版本号固定

    public MySQLiteOpenHelper(Context context) {

       super(context, DB_Name, null, VERSION);

    }


   //在onCreate方法中创建表,只执行一次

   @Override

    public void onCreate(SQLiteDatabase db) {

       String sql = Common.NewsTable.getCreateTableSQL();

        db.execSQL(sql);

    }

   //onUpgrade更新表

   @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        //先删除原表,再调用onCreate创建新表

      db.execSQL("drop table "+ Common.NewsTable.TBL_NAME);

       onCreate(db);

    }

}


  


Common 公共类


package com.example.administrator.myapplication.util;


/**

 * Created by Administrator on 2016-9-19.

 */

public class Common {

   public static class NewsTable{

       public static final String TBL_NAME ="News";

        public static final String TBL_TITLE = "NewsTitle";

        public static final String TBL_CONTENT = "NewsContent";

       public static final String TBL_SRC = "NewsImg";

        public static final String TBL_DATE = "NewsDate";


       public static String getCreateTableSQL(){

            String sql = "create table if not exists "

                       + TBL_NAME

                       + "("

                        + " _id integer primary key autoincrement,"

                       + TBL_TITLE + " text,"

                        + TBL_CONTENT + " text,"

                       + TBL_SRC + " text,"

                      + TBL_DATE + " varchar(50)"

                      + ")";

           return sql;

       }

  }

}