SQLite 使用法门.docx

上传人:b****2 文档编号:17871883 上传时间:2023-08-04 格式:DOCX 页数:13 大小:214.65KB
下载 相关 举报
SQLite 使用法门.docx_第1页
第1页 / 共13页
SQLite 使用法门.docx_第2页
第2页 / 共13页
SQLite 使用法门.docx_第3页
第3页 / 共13页
SQLite 使用法门.docx_第4页
第4页 / 共13页
SQLite 使用法门.docx_第5页
第5页 / 共13页
SQLite 使用法门.docx_第6页
第6页 / 共13页
SQLite 使用法门.docx_第7页
第7页 / 共13页
SQLite 使用法门.docx_第8页
第8页 / 共13页
SQLite 使用法门.docx_第9页
第9页 / 共13页
SQLite 使用法门.docx_第10页
第10页 / 共13页
SQLite 使用法门.docx_第11页
第11页 / 共13页
SQLite 使用法门.docx_第12页
第12页 / 共13页
SQLite 使用法门.docx_第13页
第13页 / 共13页
亲,该文档总共13页,全部预览完了,如果喜欢就下载吧!
下载资源
资源描述

SQLite 使用法门.docx

《SQLite 使用法门.docx》由会员分享,可在线阅读,更多相关《SQLite 使用法门.docx(13页珍藏版)》请在冰点文库上搜索。

SQLite 使用法门.docx

SQLite使用法门

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

本帖最后由terryyhl于2010-6-1215:

38编辑

 每个应用程序都要使用数据,Android应用程序也不例外,Android使用开源的、与操作系统无关的SQL数据库--大名鼎鼎的SQLite。

SQLite是一款轻量级数据库,它的设计目的是嵌入式,而且它占用的资源非常少,在嵌入式设备中,可能只需要几百KB,这也是Android系统采用SQLite数据库的原因之一吧。

简介

∙轻量级

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

∙独立性

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

∙隔离性

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

∙跨平台

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

Android。

∙多语言接口

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

∙安全性

SQLite数据库通过数据库级上的独占性和共享锁来实现独立事务处理。

这意味着多个进程可以在同一时间从同一数据库读取数据,但只能有一个可以写入数据。

SQLite使用介绍

  首先先来看一下本篇例子继承SQLiteOpenHelper类实现的dbHelper类。

1.packagecom.terry;

2.

3.importandroid.content.ContentValues;

4.importandroid.content.Context;

5.importandroid.database.Cursor;

6.importandroid.database.sqlite.SQLiteDatabase;

7.importandroid.database.sqlite.SQLiteOpenHelper;

8.importandroid.database.sqlite.SQLiteDatabase.CursorFactory;

9.

10.publicclassdbHelperextendsSQLiteOpenHelper{

11.

12.  privatefinalstaticStringDATABASE_NAME="sec_db";

13.  privatefinalstaticintDATABASE_VERSION=1;

14.  privatefinalstaticStringTABLE_NAME="sec_pwd";

15.  publicfinalstaticStringFIELD_ID="_id";

16.  publicfinalstaticStringFIELD_TITLE="sec_Title";

17.  

18.  

19.  publicdbHelper(Contextcontext)

20.  {

21.      super(context,DATABASE_NAME,null,DATABASE_VERSION);

22.  }

23.  

24.  

25.    

26.  @Override

27.  publicvoidonCreate(SQLiteDatabasedb){

28.      //TODOAuto-generatedmethodstub

29.      Stringsql="Createtable"+TABLE_NAME+"("+FIELD_ID+"integerprimarykeyautoincrement,"

30.      +FIELD_TITLE+"text);";

31.      db.execSQL(sql);

32.      

33.      

34.  }

35.

36.  @Override

37.  publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){

38.      //TODOAuto-generatedmethodstub

39.      Stringsql="DROPTABLEIFEXISTS"+TABLE_NAME;

40.      db.execSQL(sql);

41.      onCreate(db);

42.  }

43.

44.  publicCursorselect()

45.  {

46.      SQLiteDatabasedb=this.getReadableDatabase();

47.      Cursorcursor=db.query(TABLE_NAME,null,null,null,null,null,  "_iddesc");

48.      returncursor;

49.  }

50.  

51.  publiclonginsert(StringTitle)

52.  {

53.      SQLiteDatabasedb=this.getWritableDatabase();

54.      ContentValuescv=newContentValues();

55.      cv.put(FIELD_TITLE,Title);

56.      longrow=db.insert(TABLE_NAME,null,cv);

57.      returnrow;

58.  }

59.  

60.  publicvoiddelete(intid)

61.  {

62.      SQLiteDatabasedb=this.getWritableDatabase();

63.      Stringwhere=FIELD_ID+"=?

";

64.      String[]whereValue={Integer.toString(id)};

65.      db.delete(TABLE_NAME,where,whereValue);

66.  }

67.  

68.  publicvoidupdate(intid,StringTitle)

69.  {

70.      SQLiteDatabasedb=this.getWritableDatabase();

71.      Stringwhere=FIELD_ID+"=?

";

72.      String[]whereValue={Integer.toString(id)};

73.      ContentValuescv=newContentValues();

74.      cv.put(FIELD_TITLE,Title);

75.      db.update(TABLE_NAME,cv,where,whereValue);

76.  }

77.  

78.  

79.  

80.  

81.}

复制代码

∙创建和打开数据库

上篇通过构造函数来创建数据库,看一下构造函数的方法

1.android.database.sqlite.SQLiteOpenHelper.SQLiteOpenHelper(Contextcontext,Stringname,CursorFactoryfactory,intversion)

2.

3.publicSQLiteOpenHelper(Contextcontext,Stringname,SQLiteDatabase.CursorFactoryfactory,intversion)

4.Since:

APILevel1

5.Createahelperobjecttocreate,open,and/ormanageadatabase.ThedatabaseisnotactuallycreatedoropeneduntiloneofgetWritableDatabase()orgetReadableDatabase()iscalled.

6.

7.Parameters

8.context  tousetoopenorcreatethedatabase

9.name  ofthedatabasefile,ornullforanin-memorydatabase

10.factory  touseforcreatingcursorobjects,ornullforthedefault

11.version  numberofthedatabase(startingat1);ifthedatabaseisolder,onUpgrade(SQLiteDatabase,int,int)willbeusedtoupgradethedatabase  

12.

13.PublicMethods

复制代码

大体可以理成如下:

如果进入此函数,不存在此数据库则创建,如果存在此数据库则打开连接,只要进入此方法就可以用打开的连接获得getWritableDatabase()或getReadableDatabase()这两个方法。

∙创建表--》CreateTable

一个数据库中可以包含多个表,每一条数据都存在指定的表中,要创建可以通过execSQL方法来执行一条SQL语句。

上面的方法为

14.

15.

16.publicvoidonCreate(SQLiteDatabasedb){

17.      //TODOAuto-generatedmethodstub

18.      Stringsql="Createtable"+TABLE_NAME+"("+FIELD_ID+"integerprimarykeyautoincrement,"

19.      +FIELD_TITLE+"text);";

20.      db.execSQL(sql);

21.      

22.      

23.  }

复制代码

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

∙添加数据--》Insert

上面的代码封装了一个使用SQLite的insert方法,向表中添加数据,但是insert方法要求把数据都打包到ContentValues中,ContentValue其实可就是一个HashTable,Key值是字段名称,Value值是字段的值。

通过ContentValues的put方法就可以把数据库放到ContentValue对象中,然后插入到表中去。

代码为:

24.publiclonginsert(StringTitle)

25.  {

26.      SQLiteDatabasedb=this.getWritableDatabase();

27.      ContentValuescv=newContentValues();

28.      cv.put(FIELD_TITLE,Title);

29.      longrow=db.insert(TABLE_NAME,null,cv);

30.      returnrow;

31.  }

复制代码

∙删除数据--》Delete

依此类推,添加数据用Insert,那么删除数据为Delete

32.

33.

34.publicvoiddelete(intid)

35.  {

36.      SQLiteDatabasedb=this.getWritableDatabase();

37.      Stringwhere=FIELD_ID+"=?

";

38.      String[]whereValue={Integer.toString(id)};

39.      db.delete(TABLE_NAME,where,whereValue);

40.  }

复制代码

∙修改数据--》Update

41.publicvoidupdate(intid,StringTitle)

42.  {

43.      SQLiteDatabasedb=this.getWritableDatabase();

44.      Stringwhere=FIELD_ID+"=?

";

45.      String[]whereValue={Integer.toString(id)};

46.      ContentValuescv=newContentValues();

47.      cv.put(FIELD_TITLE,Title);

48.      db.update(TABLE_NAME,cv,where,whereValue);

49.  }

复制代码

可根据自己需要修改字段自行加参数。

∙查询数据--》Query

50.publicCursorselect()

51.  {

52.      SQLiteDatabasedb=this.getReadableDatabase();

53.      Cursorcursor=db.query(TABLE_NAME,null,null,null,null,null,  "_iddesc");

54.      returncursor;

55.  }

复制代码

在Android中查询数据是通过Cursor类来实现的,当我们使用SQLiteDatabase.query()方法时,会得到一个Cursor对象,Cursor指向的就是每一条数据。

它提供了很多有关查询的方法,具体截图如下:

  现在dbHelper己经封装完毕,接下来正式进入到我们实际例子中要操作的功能吧,项目运行效果图:

  这里用到了Menu做功能按钮,实例代码如下:

1.packagecom.terry;

2.

3.importandroid.app.Activity;

4.importandroid.database.Cursor;

5.importandroid.database.sqlite.SQLiteCursor;

6.importandroid.os.Bundle;

7.importandroid.view.Menu;  

8.importandroid.view.MenuItem;

9.importandroid.view.View;

10.importandroid.widget.AdapterView;

11.importandroid.widget.EditText;

12.importandroid.widget.ListAdapter;

13.importandroid.widget.ListView;

14.importandroid.widget.SimpleCursorAdapter;

15.importandroid.widget.AdapterView.OnItemClickListener;

16.importandroid.widget.AdapterView.OnItemSelectedListener;

17.

18.

19.publicclasstestDbActivityextendsActivity{

20.  

21.  privatedbHelperdb;

22.  privateCursormyCursor;

23.  privateListViewmyListView;

24.  privateEditTextmyEditText;

25.  privateint_id;

26.  protectedfinalstaticintMENU_ADD=Menu.FIRST;

27.  protectedfinalstaticintMENU_EDIT=Menu.FIRST+1;

28.  protectedfinalstaticintMENU_DELETE=Menu.FIRST+2;

29.  

30.    @Override

31.  publicbooleanonCreateOptionsMenu(Menumenu){

32.      //TODOAuto-generatedmethodstub

33.        super.onCreateOptionsMenu(menu);

34.      menu.add(Menu.NONE,MENU_ADD,0,R.string.ADD);

35.      menu.add(Menu.NONE,MENU_EDIT,0,R.string.EDIT);

36.      menu.add(Menu.NONE,MENU_DELETE,0,R.string.DELETE);

37.      returntrue;

38.  }

39.  

40.    @Override

41.  publicbooleanonOptionsItemSelected(MenuItemitem){

42.      //TODOAuto-generatedmethodstub

43.      

44.      super.onOptionsItemSelected(item);

45.      switch(item.getItemId()){

46.      caseMENU_ADD:

47.        operation("add");

48.        break;

49.      caseMENU_EDIT:

50.        operation("edit");

51.        break;

52.      caseMENU_DELETE:

53.        operation("delete");

54.        break;

55.      default:

56.        break;

57.      }

58.      returntrue;

59.  }

60.    

61.    

62.    

63.  /**Calledwhentheactivityisfirstcreated.*/

64.  @Override

65.  publicvoidonCreate(BundlesavedInstanceState){

66.      super.onCreate(savedInstanceState);

67.      setContentView(R.layout.main);

68.      myEditText=(EditText)findViewById(R.id.EditText1);

69.      myListView=(ListView)findViewById(R.id.ListView1);

70.      db=newdbHelper(testDbActivity.this);

71.      myCursor=db.select();

72.      SimpleCursorAdapteradpater=newSimpleCursorAdapter(this

73.          ,R.layout.test,myCursor,

74.          newString[]{dbHelper.FIELD_TITLE},

75.          newint[]{R.id.topTextView});

76.      myListView.setAdapter(adpater);

77.      

78.      myListView.setOnItemClickListener(newOnItemClickListener(){

79.

80.        @Override

81.        publicvoidonItemClick(AdapterView

>arg0,Viewarg1,intarg2,

82.              longarg3){

83.          //TODOAuto-generatedmethodstub

84.          myCursor.moveToPosition(arg2);

85.          _id=myCursor.getInt(0);

86.          myEditText.setText(myCursor.getString

(1));

87.        }

88.      });

89.      

90.      

91.      myListView.setOnItemSelectedListener(newOnItemSelectedListener(){

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 自然科学 > 物理

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2