android 数据库多个表,如何在Android studio数据库中创建多个表
时间: 2024-02-24 08:59:18 浏览: 81
在 Android Studio 中创建多个表,你需要在你的数据库帮助类中添加多个创建表的语句。具体步骤如下:
1. 定义一个常量来存储每个表的名称和列名:
```
public static final String TABLE_NAME_1 = "table1";
public static final String COL_1_TABLE_1 = "col1_table1";
public static final String COL_2_TABLE_1 = "col2_table1";
public static final String TABLE_NAME_2 = "table2";
public static final String COL_1_TABLE_2 = "col1_table2";
public static final String COL_2_TABLE_2 = "col2_table2";
```
2. 在你的数据库帮助类中添加创建表的语句:
```
private static final String CREATE_TABLE_1 = "CREATE TABLE " + TABLE_NAME_1 + "("
+ COL_1_TABLE_1 + " INTEGER PRIMARY KEY,"
+ COL_2_TABLE_1 + " TEXT)";
private static final String CREATE_TABLE_2 = "CREATE TABLE " + TABLE_NAME_2 + "("
+ COL_1_TABLE_2 + " INTEGER PRIMARY KEY,"
+ COL_2_TABLE_2 + " TEXT)";
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_1);
db.execSQL(CREATE_TABLE_2);
}
```
3. 在你的代码中使用你所创建的表:
```
// Inserting values into table1
ContentValues values = new ContentValues();
values.put(COL_1_TABLE_1, 1);
values.put(COL_2_TABLE_1, "value1");
long newRowId = db.insert(TABLE_NAME_1, null, values);
// Inserting values into table2
ContentValues values2 = new ContentValues();
values2.put(COL_1_TABLE_2, 1);
values2.put(COL_2_TABLE_2, "value2");
long newRowId2 = db.insert(TABLE_NAME_2, null, values2);
// Querying values from table1
Cursor cursor = db.query(TABLE_NAME_1, null, null, null, null, null, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex(COL_1_TABLE_1));
String value = cursor.getString(cursor.getColumnIndex(COL_2_TABLE_1));
Log.d(TAG, "ID: " + id + ", Value: " + value);
}
// Querying values from table2
Cursor cursor2 = db.query(TABLE_NAME_2, null, null, null, null, null, null);
while (cursor2.moveToNext()) {
int id = cursor2.getInt(cursor2.getColumnIndex(COL_1_TABLE_2));
String value = cursor2.getString(cursor2.getColumnIndex(COL_2_TABLE_2));
Log.d(TAG, "ID: " + id + ", Value: " + value);
}
```
以上就是在 Android Studio 中创建多个表的步骤。
阅读全文