zoukankan      html  css  js  c++  java
  • 利用SQLiteOpenHelper来管理SQLite数据库 (转)

    转载自 利用SQLiteOpenHelper来管理SQLite数据库

             http://blog.csdn.net/conowen/article/details/7306545

     

    Android学习笔记(12)————利用SQLiteOpenHelper来管理SQLite数据库

     
     
     
    /********************************************************************************************
     * author:conowen@大钟                                                                                                                          
     * E-mail:conowen@hotmail.com                                                                                                             
     * http://blog.csdn.net/conowen                                                                                                              
     * 注:本文为原创,仅作为学习交流使用,转载请标明作者及出处。      

     ********************************************************************************************/

    1、SQLiteOpenHelper介绍

    通过上篇博文,http://blog.csdn.net/conowen/article/details/7276417,了解了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),onUpgrade(SQLiteDatabase, int, int) 和onOpen(SQLiteDatabase)(可选)来操作数据库。


    2、SQLiteOpenHelper()的具体用法

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

    [java] view plaincopy
     
    1. /* 
    2.  * @author:conowen 
    3.  * @date:12.2.29  
    4.  */  
    5.   
    6. package com.conowen.sqlite;  
    7.   
    8. import android.content.Context;  
    9. import android.database.sqlite.SQLiteDatabase;  
    10. import android.database.sqlite.SQLiteDatabase.CursorFactory;  
    11. import android.database.sqlite.SQLiteOpenHelper;  
    12.   
    13. public class DbHelper extends SQLiteOpenHelper{  
    14.   
    15.     public DbHelper(Context context, String name, CursorFactory factory,  
    16.             int version) {  
    17.         super(context, name, factory, version);  
    18.         // TODO Auto-generated constructor stub  
    19.     }  
    20.   
    21.     @Override  
    22.     public void onCreate(SQLiteDatabase db) {  
    23.         // TODO Auto-generated method stub  
    24.           
    25.     }  
    26.   
    27.     @Override  
    28.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
    29.         // TODO Auto-generated method stub  
    30.           
    31.     }  
    32.   
    33. }  

    方法详解

    [java] view plaincopy
     
    1. public SQLiteOpenHelper (Context context, String name, SQLiteDatabase.CursorFactory factory, int version)   
    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
    context to use to open or create the database
    name of the database file, or null for an in-memory database
    factory to use for creating cursor objects, or null for the default
    version number of the database (starting at 1); if the database is older, onUpgrade(SQLiteDatabase, int, int) will be used to upgrade the database; if the database is newer,onDowngrade(SQLiteDatabase, int, int) will be used to downgrade the database

    参数简述:

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

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

    [java] view plaincopy
     
    1. public DbHelper(Context context, String name, CursorFactory factory,  
    2.             int version) {  
    3.         super(context, name, factory, version);  
    4.         // TODO Auto-generated constructor stub  
    5.     }  

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

    3、SQLiteOpenHelper的两个主要方法

    3.1、onCreate方法

    [java] view plaincopy
     
    1. public abstract void onCreate (SQLiteDatabase db)<span class="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
    db The database.
    [java] view plaincopy
     
    1. //这样就创建一个一个table  
    2.     @Override  
    3.     public void onCreate(SQLiteDatabase db) {  
    4.         // TODO Auto-generated method stub  
    5.   
    6.          String sql = "CREATE  TABLE table_name(_id INTEGER PRIMARY KEY , filename VARCHAR, data TEXT)";  
    7.         db.execSQL(sql);  
    8.           
    9.     }  


    3.2、onUpgrade方法

    [java] view plaincopy
     
    1. public abstract void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion)  
    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
    db The database.
    oldVersion The old database version.
    newVersion The new database version.

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

    4、注意事项

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


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

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


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

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

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

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

    效果图如下

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

    [java] view plaincopy
     
    1. /*SQLiteOpenHelper类 
    2.  * @author:conowen 
    3.  * @date:12.3.1 
    4.  */  
    5. package com.conowen.sqlite;  
    6.   
    7. import android.content.Context;  
    8. import android.database.sqlite.SQLiteDatabase;  
    9. import android.database.sqlite.SQLiteDatabase.CursorFactory;  
    10. import android.database.sqlite.SQLiteOpenHelper;  
    11.   
    12. public class DbHelper extends SQLiteOpenHelper {  
    13.   
    14.     public DbHelper(Context context, String name, CursorFactory factory,  
    15.             int version) {  
    16.         super(context, name, factory, version);  
    17.         // TODO Auto-generated constructor stub  
    18.           
    19.     }  
    20.   
    21.     @Override  
    22.     public void onCreate(SQLiteDatabase db) {  
    23.         // TODO Auto-generated method stub  
    24.   
    25.         String sql = "CREATE  TABLE addressbook (_id INTEGER PRIMARY KEY , name VARCHAR, phone VARCHAR)";  
    26.         db.execSQL(sql);  
    27.   
    28.     }  
    29.   
    30.     @Override  
    31.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
    32.         // TODO Auto-generated method stub  
    33.   
    34.     }  
    35.   
    36. }  


    main.xml

    [html] view plaincopy
     
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <LinearLayout xmlns: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.   
    7.     <EditText  
    8.         android:id="@+id/name"  
    9.         android:layout_width="fill_parent"  
    10.         android:layout_height="wrap_content" />  
    11.   
    12.     <EditText  
    13.         android:id="@+id/phone"  
    14.         android:layout_width="fill_parent"  
    15.         android:layout_height="wrap_content" />  
    16.   
    17.     <LinearLayout  
    18.         android:id="@+id/linearLayout1"  
    19.         android:layout_width="fill_parent"  
    20.         android:layout_height="wrap_content" >  
    21.   
    22.         <Button  
    23.             android:id="@+id/insert"  
    24.             android:layout_width="wrap_content"  
    25.             android:layout_height="wrap_content"  
    26.             android:text="增加" />  
    27.   
    28.         <Button  
    29.             android:id="@+id/delete"  
    30.             android:layout_width="wrap_content"  
    31.             android:layout_height="wrap_content"  
    32.             android:text="删除" />  
    33.   
    34.         <Button  
    35.             android:id="@+id/update"  
    36.             android:layout_width="wrap_content"  
    37.             android:layout_height="wrap_content"  
    38.             android:text="更改" />  
    39.   
    40.         <Button  
    41.             android:id="@+id/query"  
    42.             android:layout_width="wrap_content"  
    43.             android:layout_height="wrap_content"  
    44.             android:text="查询" />  
    45.     </LinearLayout>  
    46.   
    47.     <ListView  
    48.         android:id="@+id/lv"  
    49.         android:layout_width="fill_parent"  
    50.         android:layout_height="wrap_content" >  
    51.     </ListView>  
    52.   
    53. </LinearLayout>  

    ListView的布局文件layout.xml

    [html] view plaincopy
     
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <LinearLayout xmlns: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.   
    26. </LinearLayout>  
  • 相关阅读:
    mybatis 框架 的应用之四(一对一 与 一对多)
    mybatis 框架 的应用之三(操作两张没有关联的表,存在主键和外键关系)
    mybatis 框架 的应用之二(批量添加、实现分页查询)
    hibernate 框架的简单使用
    Java c3p0 连接 MySQL
    Oracle 复制表
    web 应用中访问 Spring 具体实现
    oracle 创建表 外键约束
    oracle 通过序列实现某字段自增
    Swift数组的sort、filter、forEach、map等方法,$的使用
  • 原文地址:https://www.cnblogs.com/YangBinChina/p/3525368.html
Copyright © 2011-2022 走看看