创建和使用数据库:Android

时间:2012-10-12 06:04:18

标签: java android database

我正在开发一个应用程序,它有几个模块。 我将不得不多次访问许多模块中的相同数据库。

我的问题是哪个地方是创建数据库和表格的最佳方式和最佳位置?

喜欢......

    1. creating the required databases and tables at once while loading app or

    2. Creating db and tables in respective modules when required??
     resulting in extra lines of codes to check if db and table already 
     exists or not..

哪一个是好选择?或者还有其他更好的方法吗?

任何建议都将受到赞赏。

提前致谢:)

4 个答案:

答案 0 :(得分:3)

首先你应该创建一个类来创建一个DB Like:

package com.DB;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.webkit.WebChromeClient.CustomViewCallback;

public class DatabaseHandler_Dashboard extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "dashboard";

    // Contacts table name
    private static final String TABLE_NAME = "tbl_dashboard";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String RANK = "RANK";
    private static final String MHBHUBCD = "MHBHUBCD";
    private static final String WK1Dkts = "WK1Dkts";
    private static final String WK1Per = "WK1Per";
    private static final String WK1OnTime = "WK1OnTime";

    private static final String WK2Dkts = "WK2Dkts";    
    private static final String Wk2Per = "Wk2Per";
    private static final String WK2OnTime = "WK2OnTime";

    private static final String QTDDkts = "QTDDkts";
    private static final String QTDPer = "QTDPer";
    private static final String QTDOnTime = "QTDOnTime";

    private static final String YTDDkts = "YTDDkts";
    private static final String YTDPer = "YTDPer";
    private static final String YTDOnTime = "YTDOnTime";



    public DatabaseHandler_Dashboard(Context context) {
        // TODO Auto-generated constructor stub
        super(context, DATABASE_NAME, null, DATABASE_VERSION);  
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

        String CREATE_DEVICE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
        + RANK + " TEXT,"
        + MHBHUBCD + " TEXT,"
        + WK1Dkts + " TEXT,"
        + WK1Per + " TEXT,"
        + WK1OnTime + " TEXT,"

        + WK2Dkts + " TEXT,"
        + Wk2Per + " TEXT,"
        + WK2OnTime + " TEXT,"

        + QTDDkts + " TEXT,"
        + QTDPer + " TEXT,"
        + QTDOnTime + " TEXT,"

        + YTDDkts + " TEXT,"
        + YTDPer + " TEXT,"
        + YTDOnTime + " TEXT"
        + ")";
        db.execSQL(CREATE_DEVICE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

        // Create tables again
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Adding new Device
    public void addDevice(Contact_Dashboard device) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(RANK , device.get_RANK());

        values.put(MHBHUBCD  , device.get_MHBHUBCD ()); 

        values.put(WK1Dkts  , device.get_WK1Dkts()); 
        values.put(WK1Per  , device.get_WK1Per()); 
        values.put(WK1OnTime  , device.get_WK1OnTime()); 

        values.put(WK2Dkts  , device.get_WK2Dkts()); 
        values.put(Wk2Per   , device.get_Wk2Per()); 
        values.put(WK2OnTime  , device.get_WK2OnTime()); 

        values.put(QTDDkts  , device.get_QTDDkts()); 
        values.put(QTDPer  , device.get_QTDPer()); 
        values.put(QTDOnTime  , device.get_QTDOnTime()); 

        values.put(YTDDkts   , device.get_YTDDkts()); 
        values.put(YTDPer   , device.get_YTDPer()); 
        values.put(YTDOnTime   , device.get_YTDOnTime()); 


        // Inserting Row
        db.insert(TABLE_NAME, null, values);

        db.close(); // Closing database connection
    }





    // Getting All Devices
    public List<Contact_Dashboard> getAllDevice() {
        List<Contact_Dashboard> deviceList = new ArrayList<Contact_Dashboard>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_NAME;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor !=null)
        {
            if (cursor.moveToFirst()) {
                do {
                    Contact_Dashboard device = new Contact_Dashboard();

                    device.set_RANK(cursor.getString(0));
                    device.set_MHBHUBCD(cursor.getString(1));

                    device.set_WK1Dkts(cursor.getString(2));
                    device.set_WK1Per (cursor.getString(3));
                    device.set_WK1OnTime (cursor.getString(4));


                    device.set_WK2Dkts (cursor.getString(5));
                    device.set_Wk2Per  (cursor.getString(6));
                    device.set_WK2OnTime (cursor.getString(7));

                    device.set_QTDDkts (cursor.getString(8));
                    device.set_QTDPer (cursor.getString(9));
                    device.set_QTDOnTime (cursor.getString(10));


                    device.set_YTDDkts (cursor.getString(11));
                    device.set_YTDPer (cursor.getString(12));
                    device.set_YTDOnTime (cursor.getString(13));


                    // Adding Device to list
                    deviceList.add(device);

                } while (cursor.moveToNext());

            }

    }
        cursor.close();
        return deviceList;


}





    // Getting contacts Count
    public int get_all_data() {
        String countQuery = "SELECT  * FROM " + TABLE_NAME;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }



    public int del_all_data()
    {
        SQLiteDatabase db = this.getWritableDatabase();
         return db.delete(TABLE_NAME, null, null);

    }



    // Getting All Devices
    public List<Contact_Dashboard> getAllDevice_sort_by(String vall,String sort_type)
    {
        List<Contact_Dashboard> deviceList = new ArrayList<Contact_Dashboard>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_NAME  + " order by CAST(" + vall + " as integer)" + sort_type;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor !=null)
        {
            if (cursor.moveToFirst()) {
                do {
                    Contact_Dashboard device = new Contact_Dashboard();

                    device.set_RANK(cursor.getString(0));
                    device.set_MHBHUBCD(cursor.getString(1));

                    device.set_WK1Dkts(cursor.getString(2));
                    device.set_WK1Per (cursor.getString(3));
                    device.set_WK1OnTime (cursor.getString(4));


                    device.set_WK2Dkts (cursor.getString(5));
                    device.set_Wk2Per  (cursor.getString(6));
                    device.set_WK2OnTime (cursor.getString(7));

                    device.set_QTDDkts (cursor.getString(8));
                    device.set_QTDPer (cursor.getString(9));
                    device.set_QTDOnTime (cursor.getString(10));


                    device.set_YTDDkts (cursor.getString(11));
                    device.set_YTDPer (cursor.getString(12));
                    device.set_YTDOnTime (cursor.getString(13));


                    // Adding Device to list
                    deviceList.add(device);

                } while (cursor.moveToNext());

            }

    }
        cursor.close();
        return deviceList;


}


}

现在,在您的其他“活动”页面中,创建此类的对象,如:

DatabaseHandler_Dashboard ECDS_DB = new DatabaseHandler_Dashboard(this);

如此自动地运行该活动,那时它会使您的数据库以及检查数据库是否存在......

现在,您可以为变量&amp;在每个活动中使用DB类对象,如:

ECDS_DB.del_all_data();

    ECDS_DB.addDevice(new Contact_Dashboard(
                        ARR_RANK[i] ,
                        ARR_MHBHUBCD[i] , 

                        ARR_WK1Dkts[i] ,
                        ARR_WK1OnTime[i] ,
                        ARR_WK1Per[i] ,

                        ARR_WK2Dkts[i] ,
                        ARR_WK2OnTime[i] ,
                        ARR_Wk2Per[i] , 

                        ARR_QTDDkts[i] , 
                        ARR_QTDOnTime[i] ,
                        ARR_QTDPer[i] ,

                        ARR_YTDDkts[i] ,
                        ARR_YTDOnTime[i] ,
                        ARR_YTDPer[i] ));

试试这个&amp;不要忘记审查我...............

答案 1 :(得分:2)

如果您只在应用中使用数据库,那么我认为SQLiteOpenHelper是最佳选择。它会在您第一次使用它时创建表。 (建议您将自己的帮助程序设置为单例类以避免并发访问问题。)

如果您在两个或多个应用程序之间共享数据库,那么您应该将数据库包裹在Content Provider之后。

答案 2 :(得分:1)

使用帮助程序类进行数据库访问的最佳方法,请按照以下步骤定义数据库帮助程序:

  1. 创建一个扩展SQLiteOpenHelper的类。
  2. 覆盖onCreate(),onUpgrade()方法和构造函数。
  3. onCreate()中的
  4. 创建所有表一次,因此您不必担心以后存在表。
  5. 在onUpgrade()方法中,删除所有表,然后执行onCreate()方法。
  6. 在您的活动和服务中,无论您何时需要访问数据库,只需创建DatabaseHelper的实例,如果它是第一次调用数据库,它将创建所有表。

答案 3 :(得分:1)

@ Jeet的答案很完美,但我仍然将其添加到性能调优中。 如果您的应用更多没有。然后你应该在任何sqlDev工具中创建你的数据库并将其导出到sql文件中。并将其放入资产文件夹。

现在,

创建一个扩展SQLiteOpenHelper的新类 在onCreate()方法中检查设备上数据库是否存在。 如果您的数据库不可用,则将数据库结构文件复制到此路径。

/data/data/YOUR_PACKAGE/databases/

通过执行此操作,您将复制整个数据库,其速度比您逐个查询创建所有表的速度快10倍。