加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

利用SQLiteOpenHelper来管理SQLite数据库

发布时间:2020-12-13 00:13:56 所属栏目:百科 来源:网络整理
导读:原文出自:author:conowen * E-mail:conowen@hotmail.com * http://blog.csdn.net/conowen 1、SQLiteOpenHelper介绍 通过上篇博文,http://www.jb51.cc/article/p-hzhgfvjf-gp.html,了解了SQLite数据库的相关操作方法,但是一般在实际开发中,为了更加方
to use to open or create the database of the database file,or null for an in-memory database to use for creating cursor objects,or null for the default number of the database (starting at 1); if the database is older, will be used to upgrade the database; if the database is newer,onDowngrade(SQLiteDatabase,int) will be used to downgrade the database

参数简述:

name————表示数据库文件名(不包括文件路径),SQLiteOpenHelper类会根据这个文件名来创建数据库文件。

version————表示数据库的版本号。如果当前传入的数据库版本号比上一次创建的版本高,SQLiteOpenHelper就会调用onUpgrade()方法。


[java] view plain copy print ?
  1. publicDbHelper(Contextcontext,
  2. intversion){
  3. super(context,version);
  4. //TODOAuto-generatedconstructorstub
  5. }

以上是SQLiteOpenHelper 的构造函数,当数据库不存在时, 就会创建数据库,然后打开数据库(过程已经被封装起来了),再调用onCreate (SQLiteDatabase db)方法来执行创建表之类的操作。当数据库存在时,SQLiteOpenHelper 就不会调用onCreate (SQLiteDatabase db)方法了,它会检测版本号,若传入的版本号高于当前的,就会执行onUpgrade()方法来更新数据库和版本号。


3、??SQLiteOpenHelper的两个主要方法

3.1、onCreate方法

[java] view plain copy print ?
  1. publicabstractvoidonCreate(SQLiteDatabasedb)<spanclass="normal"></span>

Since: API Level 1

Called when the database is created for the first time. This is where the creation of tables and the initial population of the tables should happen.

Parameters
The database. [java] view plain copy print ?
  1. //这样就创建一个一个table
  2. @Override
  3. publicvoidonCreate(SQLiteDatabasedb){
  4. //TODOAuto-generatedmethodstub
  5. Stringsql="CREATETABLEtable_name(_idINTEGERPRIMARYKEY,filenameVARCHAR,dataTEXT)";
  6. db.execSQL(sql);
  7. }



3.2、onUpgrade方法

[java] view plain copy print ?
  1. publicabstractvoidonUpgrade(SQLiteDatabasedb,intnewVersion)

Since: API Level 1

Called when the database needs to be upgraded. The implementation should use this method to drop tables,add tables,or do anything else it needs to upgrade to the new schema version.

The SQLite ALTER TABLE documentation can be found here. If you add new columns you can use ALTER TABLE to insert them into a live table. If you rename or remove columns you can use ALTER TABLE to rename the old table,then create the new table and then populate the new table with the contents of the old table.

Parameters
The database. The old database version. The new database version.

更新数据库,包括删除表,添加表等各种操作。若版本是第一版,也就是刚刚建立数据库,onUpgrade()方法里面就不用写东西,因为第一版数据库何来更新之说,以后发布的版本,数据库更新的话,可以在onUpgrade()方法添加各种更新的操作。



4、注意事项

创建完SQLiteOpenHelper 类之后,在主activity里面就可以通过SQLiteOpenHelper.getWritableDatabase()或者getReadableDatabase()方法来获取在SQLiteOpenHelper 类里面创建的数据库实例。(也就是说只有调用这两种方法才真正地实例化数据库)


getWritableDatabase() 方法————以读写方式打开数据库,如果数据库所在磁盘空间满了,而使用的又是getWritableDatabase() 方法就会出错。

因为此时数据库就只能读而不能写,


getReadableDatabase()方法————则是先以读写方式打开数据库,如果数据库的磁盘空间满了,就会打开失败,但是当打开失败后会继续尝试以只读

方式打开数据库。而不会报错


=========================================================================================================


下面演示一个以SQLite的数据库为adapter的listview例子(也可以当做通讯录小工具)

效果图如下

[java] view plain copy print ?
  1. /*主activity
  2. *@author:conowen
  3. *@date:12.3.1
  4. */
  5. packagecom.conowen.sqlite;
  6. importandroid.app.Activity;
  7. importandroid.content.ContentValues;
  8. importandroid.database.Cursor;
  9. importandroid.database.sqlite.SQLiteDatabase;
  10. importandroid.os.Bundle;
  11. importandroid.view.View;
  12. importandroid.view.View.OnClickListener;
  13. importandroid.widget.Button;
  14. importandroid.widget.EditText;
  15. importandroid.widget.ListAdapter;
  16. importandroid.widget.ListView;
  17. importandroid.widget.SimpleCursorAdapter;
  18. importandroid.widget.Toast;
  19. publicclassSqliteActivityextendsActivity{
  20. SQLiteDatabasesqldb;
  21. publicStringDB_NAME="sql.db";
  22. publicStringDB_TABLE="num";
  23. publicintDB_VERSION=1;
  24. finalDbHelperhelper=newDbHelper(this,DB_NAME,null,DB_VERSION);
  25. //DbHelper类在DbHelper.java文件里面创建的
  26. /**Calledwhentheactivityisfirstcreated.*/
  27. @Override
  28. publicvoidonCreate(BundlesavedInstanceState){
  29. super.onCreate(savedInstanceState);
  30. setContentView(R.layout.main);
  31. sqldb=helper.getWritableDatabase();
  32. //通过helper的getWritableDatabase()得到SQLiteOpenHelper所创建的数据库
  33. Buttoninsert=(Button)findViewById(R.id.insert);
  34. Buttondelete=(Button)findViewById(R.id.delete);
  35. Buttonupdate=(Button)findViewById(R.id.update);
  36. Buttonquery=(Button)findViewById(R.id.query);
  37. finalContentValuescv=newContentValues();
  38. //ContentValues是“添加”和“更新”两个操作的数据载体
  39. updatelistview();//更新listview
  40. //添加insert
  41. insert.setOnClickListener(newOnClickListener(){
  42. @Override
  43. publicvoidonClick(Viewv){
  44. //TODOAuto-generatedmethodstub
  45. EditTextet_name=(EditText)findViewById(R.id.name);
  46. EditTextet_phone=(EditText)findViewById(R.id.phone);
  47. cv.put("name",et_name.getText().toString());
  48. cv.put("phone",et_phone.getText().toString());
  49. //name和phone为列名
  50. longres=sqldb.insert("addressbook",cv);//插入数据
  51. if(res==-1){
  52. Toast.makeText(SqliteActivity.this,"添加失败",
  53. Toast.LENGTH_SHORT).show();
  54. }else{
  55. Toast.makeText(SqliteActivity.this,"添加成功",
  56. Toast.LENGTH_SHORT).show();
  57. }
  58. updatelistview();//更新listview
  59. }
  60. });
  61. //删除
  62. delete.setOnClickListener(newOnClickListener(){
  63. @Override
  64. publicvoidonClick(Viewv){
  65. //TODOAuto-generatedmethodstub
  66. intres=sqldb.delete("addressbook","name='大钟'",null);
  67. //删除列名name,行名为“大钟”的,这一行的所有数据,null表示这一行的所有数据
  68. //若第二个参数为null,则删除表中所有列对应的所有行的数据,也就是把table清空了。
  69. //name='大钟',大钟要单引号的
  70. //返回值为删除的行数
  71. if(res==0){
  72. Toast.makeText(SqliteActivity.this,"删除失败",
  73. Toast.LENGTH_SHORT).show();
  74. }else{
  75. Toast.makeText(SqliteActivity.this,"成删除了"+res+"行的数据",
  76. Toast.LENGTH_SHORT).show();
  77. }
  78. updatelistview();//更新listview
  79. }
  80. });
  81. //更改
  82. update.setOnClickListener(newOnClickListener(){
  83. @Override
  84. publicvoidonClick(Viewv){
  85. //TODOAuto-generatedmethodstub
  86. cv.put("name","大钟");
  87. cv.put("phone","1361234567");
  88. intres=sqldb.update("addressbook",cv,"name='张三'",null);
  89. //把name=张三所在行的数据,全部更新为ContentValues所对应的数据
  90. //返回时为成功更新的行数
  91. Toast.makeText(SqliteActivity.this,"成功更新了"+res+"行的数据",
  92. Toast.LENGTH_SHORT).show();
  93. updatelistview();//更新listview
  94. }
  95. });
  96. //查询
  97. query.setOnClickListener(newOnClickListener(){
  98. @Override
  99. publicvoidonClick(Viewv){
  100. //TODOAuto-generatedmethodstub
  101. Cursorcr=sqldb.query("addressbook",
  102. null,null);
  103. //返回名为addressbook的表的所有数据
  104. Toast.makeText(SqliteActivity.this,
  105. "一共有"+cr.getCount()+"条记录",Toast.LENGTH_SHORT)
  106. .show();
  107. updatelistview();//更新listview
  108. }
  109. });
  110. }
  111. //更新listview
  112. publicvoidupdatelistview(){
  113. ListViewlv=(ListView)findViewById(R.id.lv);
  114. finalCursorcr=sqldb.query("addressbook",
  115. null,null);
  116. String[]ColumnNames=cr.getColumnNames();
  117. //ColumnNames为数据库的表的列名,getColumnNames()为得到指定table的所有列名
  118. ListAdapteradapter=newSimpleCursorAdapter(this,R.layout.layout,
  119. cr,ColumnNames,newint[]{R.id.tv1,R.id.tv2,R.id.tv3});
  120. //layout为listView的布局文件,包括三个TextView,用来显示三个列名所对应的值
  121. //ColumnNames为数据库的表的列名
  122. //最后一个参数是int[]类型的,为view类型的id,用来显示ColumnNames列名所对应的值。view的类型为TextView
  123. lv.setAdapter(adapter);
  124. }
  125. }

[java] view plain copy print ?
  1. /*??SQLiteOpenHelper类
  2. *@author:conowen
  3. *@date:12.3.1
  4. */
  5. packagecom.conowen.sqlite;
  6. importandroid.content.Context;
  7. importandroid.database.sqlite.SQLiteDatabase;
  8. importandroid.database.sqlite.SQLiteDatabase.CursorFactory;
  9. importandroid.database.sqlite.SQLiteOpenHelper;
  10. publicclassDbHelperextendsSQLiteOpenHelper{
  11. publicDbHelper(Contextcontext,
  12. intversion){
  13. super(context,version);
  14. //TODOAuto-generatedconstructorstub
  15. }
  16. @Override
  17. publicvoidonCreate(SQLiteDatabasedb){
  18. //TODOAuto-generatedmethodstub
  19. Stringsql="CREATETABLEaddressbook(_idINTEGERPRIMARYKEY,nameVARCHAR,phoneVARCHAR)";
  20. db.execSQL(sql);
  21. }
  22. @Override
  23. publicvoidonUpgrade(SQLiteDatabasedb,intnewVersion){
  24. //TODOAuto-generatedmethodstub
  25. }
  26. }


main.xml


[html] view plain copy print ?
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical">
  6. <EditText
  7. android:id="@+id/name"
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"/>
  10. <EditText
  11. android:id="@+id/phone"
  12. android:layout_width="fill_parent"
  13. android:layout_height="wrap_content"/>
  14. <LinearLayout
  15. android:id="@+id/linearLayout1"
  16. android:layout_width="fill_parent"
  17. android:layout_height="wrap_content">
  18. <Button
  19. android:id="@+id/insert"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:text="增加"/>
  23. <Button
  24. android:id="@+id/delete"
  25. android:layout_width="wrap_content"
  26. android:layout_height="wrap_content"
  27. android:text="删除"/>
  28. <Button
  29. android:id="@+id/update"
  30. android:layout_width="wrap_content"
  31. android:layout_height="wrap_content"
  32. android:text="更改"/>
  33. <Button
  34. android:id="@+id/query"
  35. android:layout_width="wrap_content"
  36. android:layout_height="wrap_content"
  37. android:text="查询"/>
  38. </LinearLayout>
  39. <ListView
  40. android:id="@+id/lv"
  41. android:layout_width="fill_parent"
  42. android:layout_height="wrap_content">
  43. </ListView>
  44. </LinearLayout>


ListView的布局文件layout.xml

[html] view plain copy print ?
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="horizontal">
  6. <TextView
  7. android:id="@+id/tv1"
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:textSize="20sp"
  11. android:width="50px"/>
  12. <TextView
  13. android:id="@+id/tv2"
  14. android:layout_width="wrap_content"
  15. android:layout_height="wrap_content"
  16. android:textSize="20sp"
  17. android:width="50px"
  18. />
  19. <TextView
  20. android:id="@+id/tv3"
  21. android:layout_width="wrap_content"
  22. android:layout_height="wrap_content"
  23. android:textSize="20sp"
  24. android:width="150px"/>
  25. </LinearLayout>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

原文出自:author:conowen
* E-mail:conowen@hotmail.com
*
http://blog.csdn.net/conowen

1、SQLiteOpenHelper介绍

通过上篇博文,http://www.52php.cn/article/p-hzhgfvjf-gp.html,了解了SQLite数据库的相关操作方法,但是一般在实际开发中,为了更加方便地管理、维护、升级数据库,需要通过继承SQLiteOpenHelper类来管理SQLite数据库。


关于SQLiteOpenHelper的官方说明如下:

A helper class to manage database creation and version management.

You create a subclass implementing onCreate(SQLiteDatabase),onUpgrade(SQLiteDatabase,int,int) and optionallyonOpen(SQLiteDatabase),and this class takes care of opening the database if it exists,creating it if it does not,and upgrading it as necessary. Transactions are used to make sure the database is always in a sensible state.

This class makes it easy for ContentProvider implementations to defer opening and upgrading the database until first use,to avoid blocking application startup with long-running database upgrades.

For an example,see the NotePadProvider class in the NotePad sample application,in thesamples/ directory of the SDK.

简单翻译:SQLiteOpenHelper可以创建数据库,和管理数据库的版本。

在继承SQLiteOpenHelper的类(extends SQLiteOpenHelper)里面,通过复写onCreate(SQLiteDatabase),int) 和onOpen(SQLiteDatabase)(可选)来操作数据库。



2、SQLiteOpenHelper()的具体用法

创建一个新的class如下所示,onCreate(SQLiteDatabase db)和onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion)方法会被自动添加。

[java] view plain copy print ?
  1. /*
  2. *@author:conowen
  3. *@date:12.2.29
  4. */
  5. packagecom.conowen.sqlite;
  6. importandroid.content.Context;
  7. importandroid.database.sqlite.SQLiteDatabase;
  8. importandroid.database.sqlite.SQLiteDatabase.CursorFactory;
  9. importandroid.database.sqlite.SQLiteOpenHelper;
  10. publicclassDbHelperextendsSQLiteOpenHelper{
  11. publicDbHelper(Contextcontext,Stringname,CursorFactoryfactory,
  12. intversion){
  13. super(context,name,factory,version);
  14. //TODOAuto-generatedconstructorstub
  15. }
  16. @Override
  17. publicvoidonCreate(SQLiteDatabasedb){
  18. //TODOAuto-generatedmethodstub
  19. }
  20. @Override
  21. publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){
  22. //TODOAuto-generatedmethodstub
  23. }
  24. }

方法详解

[java] view plain copy print ?
  1. publicSQLiteOpenHelper(Contextcontext,SQLiteDatabase.CursorFactoryfactory,intversion)

Since: API Level 1

Create a helper object to create,open,and/or manage a database. This method always returns very quickly. The database is not actually created or opened until one ofgetWritableDatabase() orgetReadableDatabase() is called.

Parameters
contextnamefactoryversion
db
dboldVersionnewVersion
    推荐文章
      热点阅读