android sqlite 创建多个表
时间: 2023-05-03 07:03:40 浏览: 95
Android SQLite是Android操作系统自带的轻量级关系型数据库管理系统,可以在应用程序中使用SQLite实现数据的存储和管理。创建多个表可以实现更为复杂的数据结构和存储方式。
在Android SQLite中创建多个表需要以下几个步骤:
1.创建一个SQLiteOpenHelper类,继承自SQLiteOpenHelper,该类需要在构造函数中传递四个参数:
public class MyDatabaseHelper extends SQLiteOpenHelper{
public static final String DB_NAME = "mydatabase.db";
public static final int DB_VERSION = 1;
public MyDatabaseHelper(Context context){
super(context, DB_NAME, null, DB_VERSION);
}
}
2.在onCreate()方法中,通过execSQL()方法创建多个表:
@Override
public void onCreate(SQLiteDatabase db) {
String sql1 = "create table table1 (_id integer primary key autoincrement, name text, age integer)";
db.execSQL(sql1);
String sql2 = "create table table2 (_id integer primary key autoincrement, address text, phone text)";
db.execSQL(sql2);
}
3.在onUpgrade()方法中,实现表的数据迁移和版本升级:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql1 = "drop table if exists table1";
db.execSQL(sql1);
String sql2 = "drop table if exists table2";
db.execSQL(sql2);
onCreate(db);
}
以上就是Android SQLite创建多个表的基本步骤。在具体实现中,还需要注意表结构的设计和数据的操作方法等。