gpt4 book ai didi

android - Android中简单的数据库访问方法

转载 作者:行者123 更新时间:2023-11-29 00:29:01 26 4
gpt4 key购买 nike

我目前正在学习适用于 Android 的 SQLite 访问教程。它向我展示了一个示例“DBAdapter”类,如下所示:

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;
}
}

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

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

因为我肯定需要进行大量调用才能访问数据库,所以我希望它不那么冗长。我试图创建一个静态类(因此我不必实例化它),但不能,因为 DBAdapter 类期望在上下文中传递(例如;this)。

我想制作一个允许我使用一行代码执行数据库操作的类,例如,dbClass.insertContact("name");dbClass。 getContacts();。我不想每次都实例化类、打开连接和关闭连接——但我似乎无法将其与静态函数一起使用。谁能给我任何想法?

最佳答案

这个方法很适合我。

创建一个 DataHelper打开数据库并维护对数据库对象的引用并公开数据库的类。

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
}

}

}

Extend your Application class并将您的数据对象存储为其中的静态字段。修改您的 Android.manifest 以使用您的自定义应用类而不是默认类。

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();
}
}

任何需要数据访问的类都可以引用这个对象并获得对打开的数据库的引用。然后,您可以将所有数据访问代码放在它相关的类中。

例如在您的 Contact 类中,您可以有一个“Save”方法,该方法从 Application 类获取数据库并执行所有必要的命令以保存联系人详细信息。这会将所有数据访问代码保存在它相关的类中。即所有修改联系人的代码都在您的联系人类中。

public class contact {

public void Save() {

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

}

}

由于 DataHelper 在静态字段中,您可以随时随地访问它,并且它已经拥有来自应用程序类的自己的上下文。

请注意,为简单起见,以上内容不包括任何错误处理。

关于android - Android中简单的数据库访问方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17234451/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com