android 使用sqlite几种方式。
时间:2010-09-11 来源:chinachen
1.The basic databaseHandler
先看代码:
package huuah.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.SQLException;
public class databaseHelper extends SQLiteOpenHelper {
private static final String DBNAME = "myfancydatabase";
private databaseHelper myDBHelper;
private SQLiteDatabase myDB;
private final Context myContext;
public databaseHelper(Context context) {
super(context, DBNAME, null, 2);
this.myContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public databaseHelper open() throws SQLException {
myDBHelper = new databaseHelper(myContext);
myDB = myDBHelper.getWritableDatabase();
return this;
}
}
databaseHandler 是连接sqlite最基本类。当 open()函数被调用时,android会创建一个新的数据库,并命名为myfancydatabase
且数据库文件路径是 /data/data/你的包名/databases/.
2. Copying from assets to database path
把已有的数据库拷贝到程序的数据库目录。
看代码:
public void createDatabase() throws IOException {
InputStream assetsDB = myContext.getAssets().open("localdb");
OutputStream dbOut = new FileOutputStream("/data/data/huuah.db/database/myfancydatabase");
byte[] buffer = new byte[1024];
int length;
while ((length = assetsDB.read(buffer))>0){
dbOut.write(buffer, 0, length);
}
dbOut.flush();
dbOut.close();
assetsDB.close();
}
这个函数,也就是拷贝一个文件到指定目录。作用是 将assets 里的localdb数据库拷贝到程序默认数据库目录下
/data/data/包名/databases/新数据库名
OK 拷贝完成, 就可直接使用了。
3。 Using DDMS or the ADB tool
使用DDMS
myeclipse 菜单 选择Perspective ->Other->DDMS
OK 弹出DDMS 界面, 其中File Explorer 窗口 就可以导入导出数据库文件或其他类型文件。
OK 三种方式,目的一致,根据实际需要选择。没有特别的要求, 比如需要初始化大量的数据,可以选择第2种方式。 作为配置参数 可以选第一种,或者XML。。。 个人意见,欢迎讨论。
相关阅读 更多 +