【发布时间】:2012-08-15 05:29:40
【问题描述】:
我需要知道如何将 2 个表连接在一起。我不知道如何加入表格,因为我是新手。
我创建了 AnniversaryDBAdapter.class,在其中我在一个数据库中创建了 5 个表。我只需要加入 2 个表,比如加入 buddiesList 表和喜欢表。
以下是 AnniversaryDBAdapter.class 的代码
public class AnniversaryDBAdapter
{
private static final String DATABASE_NAME = "AllTables";
private static final int DATABASE_VERSION = 2;
private static final String CREATE_TABLE_BUDDIESLIST = " create table buddiesList(name_id integer primary key autoincrement, name text not null);";
private static final String CREATE_TABLE_LIKES = " create table likes(name_id integer primary key autoincrement,likes text not null);";
private static final String CREATE_TABLE_DISLIKES = " create table dislikes(name_id integer primary key autoincrement, dislikes text not null);";
private static final String CREATE_TABLE_EVENTS = "create table events(date_id integer primary key autoincrement, name_id text not null, date text not null, title_id text not null, starttime text not null, endtime text not null);";
private static final String CREATE_TABLE_TITLE = "create table titles(title_id integer primary key autoincrement, name text not null, image text not null);";
private final Context context;
private static final String TAG = "DBAdapter";
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public AnniversaryDBAdapter(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)
{
db.execSQL(CREATE_TABLE_BUDDIESLIST);
db.execSQL(CREATE_TABLE_LIKES);
db.execSQL(CREATE_TABLE_EVENTS);
db.execSQL(CREATE_TABLE_TITLE);
}
@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");
onCreate(db);
}
}
public AnniversaryDBAdapter open() throws SQLException
{
this.db = this.DBHelper.getWritableDatabase();
return this;
}
public void close()
{
this.DBHelper.close();
}
}
【问题讨论】:
-
您的
buddiesList和likes表实际上没有任何适合加入的内容 - 如果您打算将name_id用作likes中的外键,则它不应该是自动递增的主键。 -
哦,好吧。如何通过编码为外键设置 name_id。例如,我在 buddiesList 中将 name_id 设置为整数主键自动增量,并将 name 设置为 text not null。
-
您通常不会通过编码来实现 - 最佳实践是使用 SQL 将其定义为外键 - 并利用级联等内置功能来清理
likes当buddiesList中的一行被删除时的表。 -
你的意思是我需要在 SQL 软件中定义为外键吗?我使用的是 SQLiteDatabase Browser v2.0,但它是使用 3.6.18 版构建的。你说的内置功能是什么意思,比如级联清理喜欢表?我正在使用 Eclipse IDE 3.7 版 Indigo
-
该工具使用了一个非常旧版本的 SQLite - 而外键的语法存在于 3.6.18 支持中,直到 3.6.19 才添加。您可能应该考虑自己设计表格 - 对于示例中的小表格,它可能会更好。您的目标是哪些 Android 版本?
标签: android database sqlite join