在Android的简单的数据库访问方法 [英] Easy database access methods in Android

查看:106
本文介绍了在Android的简单的数据库访问方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前以下为Android一个SQLite访问教程。它有psented给我一个样品DBAdapter类$ P $,如下:

I am currently following a SQLite access tutorial for Android. It has presented to me a sample 'DBAdapter' class, as below:

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {
static final String KEY_ROWID = "_id";
static final String KEY_NAME = "name";
static final String KEY_EMAIL = "email";
static final String TAG = "DBAdapter";

static final String DATABASE_NAME = "MyDB";
static final String DATABASE_TABLE = "contacts";
static final int DATABASE_VERSION = 1;

static final String DATABASE_CREATE =
        "create table contacts (_id integer primary key autoincrement, "
        + "name text not null, email text not null);";

final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;

public DBAdapter(Context ctx)
{
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
}

private static class DatabaseHelper extends SQLiteOpenHelper
{
    DatabaseHelper(Context context)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        try
        {
            db.execSQL(DATABASE_CREATE);
        }
        catch (SQLException ex)
        {
            ex.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS contacts");
        onCreate(db);
    }
}

//---opens the database---
public DBAdapter open() throws SQLException
{
    db = DBHelper.getWritableDatabase();
    return this;
}

//---closes the database---
public void close()
{
    DBHelper.close();       
}   

//---insert a contact into the database---
public long insertContact(String name, String email)
{
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_NAME,  name);
    initialValues.put(KEY_EMAIL,  email);
    return db.insert(DATABASE_TABLE,  null,  initialValues);
}

//---deletes a particular contact---
public boolean deleteContact(long rowId)
{
    return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;        
}

//---retrieves all the contacts---
public Cursor getAllContacts()
{
    return db.query(DATABASE_TABLE,  new String[] {KEY_ROWID,  KEY_NAME,  KEY_EMAIL}, null, null, null, null, null);
}

//---retrieves a particular contact---
public Cursor getContact(long rowId) throws SQLException
{
    Cursor mCursor =
            db.query(true,  DATABASE_TABLE,  new String[] {KEY_ROWID,  KEY_NAME,  KEY_EMAIL}, KEY_ROWID + "="
                    + rowId, null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

//---updates a contact---
public boolean updateContact(long rowId, String name, String email)
{
    ContentValues args = new ContentValues();
    args.put(KEY_NAME,  name);
    args.put(KEY_EMAIL,  email);
    return db.update(DATABASE_TABLE,  args,  KEY_ROWID + "=" + rowId,  null) > 0;
}
}

现在,如果我想使用这个类来插入联系人,我需要编写如下:

Now if I wanted to use this class to insert a contact, I would need to write the following:

DBAdapter db = new DBAdapter(this);
db.open();
long id = db.insertContact("name", "email");
db.close();

由于我肯定会需要做大量的电话来访问数据库,我宁愿这是更简洁。我试图做一个静态类(所以我不会有实例的话),但不能作为DBAdapter类是预期的情况下传递(例如,

我想提出一个类,将让我用code,例如, dbClass.insertContact(名字)单行执行数据库操作; dbClass.getContacts(); 。我不想实例化类,打开连接,每一次关闭连接 - 但我似乎无法使用这个带有静电功能。任何人都可以给我任何想法?

I'd like to make a class that will allow me perform database operations with a single line of code, eg, dbClass.insertContact("name");, or dbClass.getContacts();. I don't want to instantiate the class, open the connection and close the connection every time - and yet I can't seem to use this with a static function. Could anyone give me any ideas?

推荐答案

这个方法很适合我。

创建,打开你的数据库,并保持 DataHelper 类一个参考所述数据库对象和它公开的数据库。

Create a DataHelper class that opens your database and maintains a reference to the database object and which exposes the database.

public class CustomDataHelper {

private static final int DATABASE_VERSION = 30;
public SQLiteDatabase db = null;

public CustomDataHelper() {

    SQLiteOpenHelper o = new MyOpenHelper(CustomApp.app, "MyData.db");
    this.db = o.getWritableDatabase();

}

    // Rest of standard DataHelper class

private class MyOpenHelper extends SQLiteOpenHelper {

    MyOpenHelper(Context context,String DatabaseName) {
        super(context, DatabaseName, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
              // Standard data code here
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
              // Standard data code here
    }

}

}

扩展应用程序类和你的数据对象存储为在其中一个静态字段。修改您的Andr​​oid.manifest来使用,而不是默认的自定义应用程序的类。

Extend your Application class and store your Data object as a static field within it. Modify your Android.manifest to use your custom app class instead of the default one.

public class CustomApp extends Application {

public static CustomDataHelper data; // Access the data class from anywhere

public static CustomApp app; // Access the application context from anywhere

@Override
public void onCreate() {
    super.onCreate();

    app = this;
    data = new CustomDataHelper();
}
}

这需要数据访问可以参考该对象,并得到一个参考打开数据库的任何类。然后,你可以把它涉及到类中所有的数据访问code。

Any classes that require data access can refer to this object and get a reference to the open database. You can then put all data access code within the class that it relates to.

例如。在您的联系人类,你可以有一个保存方法会从应用程序级的数据库,并执行所有必要的命令来保存联系人信息。这样可以使您所有的数据访问code,因为它涉及到的类。即所有code表示修改联系人的联系人类中。

e.g. In your Contact class you could have a "Save" method that gets the database from the Application class and performs all necessary commands to save the contact details. This keeps all your data access code in the classes that it relates to. i.e All code that modifies contacts is within your contact class.

public class contact {

    public void Save() {

        CustomApp.data.db.execSQL("Your SQL Here");
        // etc

    }

}

由于DataHelper是一个静态字段,你可以从任何地方随时访问它,它已经拥有了自己的上下文从应用程序类。

As the DataHelper is in a static field, you can access it from anywhere at any time and it already has its own context from the Application Class.

请注意上述不包括任何错误处理简单起见

Note the above excludes any error handling for the sake of simplicity.

这篇关于在Android的简单的数据库访问方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆