Android 小项目之--SQLite 使用法门 (附源码)

来源:互联网 发布:淘宝订单信息查询 编辑:程序博客网 时间:2024/04/30 17:54
每个应用程序都要使用数据,Android应用程序也不例外,Android使用开源的、与操作系统无关的SQL数据库 --大名鼎鼎的SQLite。SQLite是一款轻量级数据库,它的设计目的是嵌入式,而且它占用的资源非常少,在嵌入式设备中,可能只需要几百KB,这也是 Android 系统采用 SQLite 数据库的原因之一吧。

  简介轻量级使用 SQLite 只需要带一个动态库,就可以享受它的全部功能,而且那个动态库的尺寸想当小。

  独立性SQLite 数据库的核心引擎不需要依赖第三方软件,也不需要所谓的“安装”。

  隔离性SQLite 数据库中所有的信息(比如表、视图、触发器等)都包含在一个文件夹内,方便管理和维护。

  跨平台SQLite 目前支持大部分操作系统,不至电脑操作系统更在众多的手机系统也是能够运行,比如:Android。

  多语言接口SQLite 数据库支持多语言编程接口。

  安全性SQLite 数据库通过数据库级上的独占性和共享锁来实现独立事务处理。这意味着多个进程可以在同一时间从同一数据库读取数据,但只能有一个可以写入数据。

  SQLite使用介绍首先先来看一下本篇例子继承 SQLiteOpenHelper 类实现的 dbHelper 类。
  1. package com.terry;

  2. import android.content.ContentValues;
  3. import android.content.Context;
  4. import android.database.Cursor;
  5. import android.database.sqlite.SQLiteDatabase;
  6. import android.database.sqlite.SQLiteOpenHelper;
  7. import android.database.sqlite.SQLiteDatabase.CursorFactory;

  8. public class dbHelper extends SQLiteOpenHelper {

  9.     private final static String DATABASE_NAME="sec_db";
  10.     private final static int DATABASE_VERSION=1;
  11.     private final static String TABLE_NAME="sec_pwd";
  12.     public final static String FIELD_ID="_id"; 
  13.     public final static String FIELD_TITLE="sec_Title";
  14.     
  15.     
  16.     public dbHelper(Context context)
  17.     {
  18.         super(context, DATABASE_NAME,null, DATABASE_VERSION);
  19.     }
  20.     
  21.     
  22.      
  23.     @Override
  24.     public void onCreate(SQLiteDatabase db) {
  25.         // TODO Auto-generated method stub
  26.         String sql="Create table "+TABLE_NAME+"("+FIELD_ID+" integer primary key autoincrement,"
  27.         +FIELD_TITLE+" text );";
  28.         db.execSQL(sql);
  29.         
  30.          
  31.     }

  32.     @Override
  33.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  34.         // TODO Auto-generated method stub
  35.         String sql=" DROP TABLE IF EXISTS "+TABLE_NAME;
  36.         db.execSQL(sql);
  37.         onCreate(db);
  38.     }

  39.     public Cursor select()
  40.     {
  41.         SQLiteDatabase db=this.getReadableDatabase();
  42.         Cursor cursor=db.query(TABLE_NAME, null, null, null, null, null,  " _id desc");
  43.         return cursor;
  44.     }
  45.     
  46.     public long insert(String Title)
  47.     {
  48.         SQLiteDatabase db=this.getWritableDatabase();
  49.         ContentValues cv=new ContentValues(); 
  50.         cv.put(FIELD_TITLE, Title);
  51.         long row=db.insert(TABLE_NAME, null, cv);
  52.         return row;
  53.     }
  54.     
  55.     public void delete(int id)
  56.     {
  57.         SQLiteDatabase db=this.getWritableDatabase();
  58.         String where=FIELD_ID+"=?";
  59.         String[] whereValue={Integer.toString(id)};
  60.         db.delete(TABLE_NAME, where, whereValue);
  61.     }
  62.     
  63.     public void update(int id,String Title)
  64.     {
  65.         SQLiteDatabase db=this.getWritableDatabase();
  66.         String where=FIELD_ID+"=?";
  67.         String[] whereValue={Integer.toString(id)};
  68.         ContentValues cv=new ContentValues(); 
  69.         cv.put(FIELD_TITLE, Title);
  70.         db.update(TABLE_NAME, cv, where, whereValue);
  71.     }
  72.     
  73.     
  74.     
  75.     
  76. }
复制代码

  创建和打开数据库上篇通过构造函数来创建数据库,看一下构造函数的方法
  1. android.database.sqlite.SQLiteOpenHelper.SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version)

  2. public SQLiteOpenHelper (Context context, String name, SQLiteDatabase.CursorFactory factory, int version) 
  3. Since: API Level 1 
  4. Create a helper object to create, open, and/or manage a database. The database is not actually created or opened until one of getWritableDatabase() or getReadableDatabase() is called.

  5. Parameters
  6. context  to use to open or create the database 
  7. name  of the database file, or null for an in-memory database 
  8. factory  to use for creating cursor objects, or null for the default 
  9. version  number of the database (starting at 1); if the database is older, onUpgrade(SQLiteDatabase, int, int) will be used to upgrade the database  

  10. Public Methods
复制代码
  大体可以理成如下:如果进入此函数,不存在此数据库则创建,如果存在此数据库则打开连接,只要进入此方法就可以用打开的连接获得getWritableDatabase()或getReadableDatabase()这两个方法。

  创建表--》Create Table一个数据库中可以包含多个表,每一条数据都存在指定的表中,要创建可以通过 execSQL 方法来执行一条 SQL 语句。上面的方法为
  1. public void onCreate(SQLiteDatabase db) {
  2.         // TODO Auto-generated method stub
  3.         String sql="Create table "+TABLE_NAME+"("+FIELD_ID+" integer primary key autoincrement,"
  4.         +FIELD_TITLE+" text );";
  5.         db.execSQL(sql);
  6.         
  7.          
  8.     }
复制代码

  上面代码创建了表名为“sec_pwd” 的数据表,表内存在一个 integer 类型的主键和一个 text 类型的字段,并执行创建该表。

  添加数据--》Insert上面的代码封装了一个使用SQLite 的 insert 方法,向表中添加数据,但是insert 方法要求把数据都打包到 ContentValues 中, ContentValue 其实可就是一个 HashTable,Key值是字段名称,Value 值是字段的值。通过 ContentValues 的put 方法就可以把数据库放到 ContentValue 对象中,然后插入到表中去。代码为:

  1. public long insert(String Title)
  2.     {
  3.         SQLiteDatabase db=this.getWritableDatabase();
  4.         ContentValues cv=new ContentValues(); 
  5.         cv.put(FIELD_TITLE, Title);
  6.         long row=db.insert(TABLE_NAME, null, cv);
  7.         return row;
  8.     }
复制代码
  删除数据--》Delete依此类推,添加数据用Insert,那么删除数据为Delete
  1. public void delete(int id)
  2.     {
  3.         SQLiteDatabase db=this.getWritableDatabase();
  4.         String where=FIELD_ID+"=?";
  5.         String[] whereValue={Integer.toString(id)};
  6.         db.delete(TABLE_NAME, where, whereValue);
  7.     }
复制代码
  修改数据--》Update
  1. public void update(int id,String Title)
  2.     {
  3.         SQLiteDatabase db=this.getWritableDatabase();
  4.         String where=FIELD_ID+"=?";
  5.         String[] whereValue={Integer.toString(id)};
  6.         ContentValues cv=new ContentValues(); 
  7.         cv.put(FIELD_TITLE, Title);
  8.         db.update(TABLE_NAME, cv, where, whereValue);
  9.     }
复制代码
  可根据自己需要修改字段自行加参数。

  查询数据--》Query
  1. public Cursor select()
  2.     {
  3.         SQLiteDatabase db=this.getReadableDatabase();
  4.         Cursor cursor=db.query(TABLE_NAME, null, null, null, null, null,  " _id desc");
  5.         return cursor;
  6.     }
复制代码
  • 在 Android 中查询数据是通过 Cursor 类来实现的,当我们使用SQLiteDatabase.query()方法时,会得到一个Cursor对象,Cursor指向的就是每一条数据。它提供了很多有关查询的方法,具体截图如下: 
  现在dbHelper己经封装完毕,接下来正式进入到我们实际例子中要操作的功能吧,项目运行效果图:
  这里用到了Menu做功能按钮,实例代码如下:
  1. package com.terry;

  2. import android.app.Activity;
  3. import android.database.Cursor;
  4. import android.database.sqlite.SQLiteCursor;
  5. import android.os.Bundle; 
  6. import android.view.Menu;  
  7. import android.view.MenuItem;
  8. import android.view.View;
  9. import android.widget.AdapterView;
  10. import android.widget.EditText;
  11. import android.widget.ListAdapter;
  12. import android.widget.ListView;
  13. import android.widget.SimpleCursorAdapter;
  14. import android.widget.AdapterView.OnItemClickListener;
  15. import android.widget.AdapterView.OnItemSelectedListener;


  16. public class testDbActivity extends Activity {
  17.     
  18.     private dbHelper db;
  19.     private Cursor myCursor;
  20.     private ListView myListView;
  21.     private EditText myEditText;
  22.     private int _id;
  23.     protected final static int MENU_ADD=Menu.FIRST;
  24.     protected final static int MENU_EDIT=Menu.FIRST+1;
  25.     protected final static int MENU_DELETE=Menu.FIRST+2;
  26.     
  27.        @Override
  28.     public boolean onCreateOptionsMenu(Menu menu) {
  29.         // TODO Auto-generated method stub
  30.            super.onCreateOptionsMenu(menu);
  31.         menu.add(Menu.NONE, MENU_ADD, 0, R.string.ADD);
  32.         menu.add(Menu.NONE, MENU_EDIT, 0,R.string.EDIT);
  33.         menu.add(Menu.NONE, MENU_DELETE, 0,R.string.DELETE);
  34.          return true;
  35.     }
  36.     
  37.        @Override
  38.     public boolean onOptionsItemSelected(MenuItem item) {
  39.         // TODO Auto-generated method stub
  40.         
  41.         super.onOptionsItemSelected(item); 
  42.         switch (item.getItemId()) {
  43.         case MENU_ADD:
  44.             operation("add");
  45.             break;
  46.         case MENU_EDIT:
  47.             operation("edit");
  48.             break;
  49.         case MENU_DELETE:
  50.             operation("delete");
  51.             break;
  52.         default:
  53.             break;
  54.         }
  55.         return true;
  56.     }
  57.        
  58.        
  59.        
  60.     /** Called when the activity is first created. */
  61.     @Override
  62.     public void onCreate(Bundle savedInstanceState) {
  63.         super.onCreate(savedInstanceState);
  64.         setContentView(R.layout.main);
  65.         myEditText=(EditText)findViewById(R.id.EditText1);
  66.         myListView=(ListView)findViewById(R.id.ListView1);
  67.         db=new dbHelper(testDbActivity.this);
  68.         myCursor=db.select();
  69.         SimpleCursorAdapter adpater=new SimpleCursorAdapter(this
  70.                 , R.layout.test, myCursor,
  71.                 new String[]{dbHelper.FIELD_TITLE},
  72.                 new int[]{R.id.topTextView});
  73.         myListView.setAdapter(adpater);
  74.         
  75.         myListView.setOnItemClickListener(new OnItemClickListener() {

  76.             @Override
  77.             public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
  78.                     long arg3) {
  79.                 // TODO Auto-generated method stub
  80.                 myCursor.moveToPosition(arg2);
  81.                 _id=myCursor.getInt(0);
  82.                 myEditText.setText(myCursor.getString(1));
  83.             }
  84.         });
  85.         
  86.         
  87.         myListView.setOnItemSelectedListener(new OnItemSelectedListener() {

  88.             @Override
  89.             public void onItemSelected(AdapterView<?> arg0, View arg1,
  90.                     int arg2, long arg3) {
  91.                 // TODO Auto-generated method stub
  92.                 SQLiteCursor sc=(SQLiteCursor)arg0.getSelectedItem();
  93.                 _id=sc.getInt(0);
  94.                 myEditText.setText(sc.getString(1));
  95.             }

  96.             @Override
  97.             public void onNothingSelected(AdapterView<?> arg0) {
  98.                 // TODO Auto-generated method stub
  99.                 
  100.             }
  101.         });
  102.     }
  103.     private void operation(String cmd)
  104.     {
  105.         if(myEditText.getText().toString().equals(""))
  106.         return;
  107.         if(cmd=="add")
  108.             db.insert( myEditText.getText().toString());
  109.         if(cmd=="edit")
  110.             db.update(_id,  myEditText.getText().toString());
  111.         if(cmd=="delete")
  112.             db.delete(_id);
  113.         myCursor.requery();
  114.         myListView.invalidateViews();
  115.         myEditText.setText("");
  116.         _id=0;
  117.         
  118.     }
  119.     
  120.    
  121.     
  122.     
  123.     
  124.     
  125.     
  126.     
  127.     
  128. }
复制代码
 至此,功能己经基本完成。
0 0
原创粉丝点击