安卓数据库 [英] android database
问题描述
如何在Android的程序打开数据库?
How to open database in Android programming ?
推荐答案
扩展SQLiteOpenHelper像这样的类:
Extend the SQLiteOpenHelper class like so:
private static class MyDbHelper extends SQLiteOpenHelper
{
public MyDbHelper(Context context, String description, CursorFactory factory, int version)
{
super(context, description, factory, version);
}
@Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(CREATE_TABLE_1);
_db.execSQL(CREATE_TABLE_2);
_db.execSQL(CREATE_TABLE_3);
..etc
}
@Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion)
{
// Log the version upgrade.
Log.w("MyDbAdapter", "Upgrading from version " + oldVersion + " to " +
newVersion + ", which will destroy all old data.");
_db.execSQL("DROP TABLE IF EXISTS " + TBL_ONE);
_db.execSQL("DROP TABLE IF EXISTS " + TBL_TWO);
_db.execSQL("DROP TABLE IF EXISTS " + TBL_THREE);
onCreate(_db);
}
}
创建使用dbhelper数据适配器类:
Create a data adapter class that uses the dbhelper:
private SQLiteDatabase db;
private MyDbHelper dbHelper;
public MyDbAdapter(Context context)
{
dbHelper = new MyDbHelper(context, DATABASE_NAME, null, DB_VERSION);
}
public MyDbAdapter open() throws SQLException
{
try
{
db = dbHelper.getWritableDatabase();
}
catch (SQLiteException ex)
{
db = dbHelper.getReadableDatabase();
}
return this;
}
public void close()
{
db.close();
}
然后就可以这样使用:
And then it can be used thus:
public class ListsDAO
{
private Context mContext;
private MyDbAdapter db;
public ListsDAO(Context context)
{
mContext = context;
db = new MyDbAdapter(mContext);
}
public List<MyObject> getAllObjects()
{
List<MyObject> objects = new ArrayList<MyObject>();
db.open();
Cursor cursor = db.getAllObjects();
if (cursor.moveToFirst())
{
...等 一旦你的光标行的名单上,你可以通过这些步骤获得的各种表中的列:
... etc Once you've got the cursor on a list of rows you can step through them getting the various columns in the table:
例如。说明= cursor.getString(descriptionColumn);
e.g. description = cursor.getString(descriptionColumn);
静态字符串,如CREATE_TABLE_1基本上都是用于创建表的SQL语句。您可能还需要一个较温和的数据库升级路线不是简单地删除所有的表,再重新创建它们。
The static strings such as CREATE_TABLE_1 are basically SQL statements for creating the tables. You may also want a less drastic database upgrade route than simply dropping all the tables and recreating them again.
这篇关于安卓数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!