我在android上使用sqlite时,我将文本插入整数列我没有收到任何错误,外键约束不起作用

时间:2016-10-05 08:47:00

标签: android sqlite

以下代码如下:我正在创建2个表:教师和证书。我希望Credentials_ID列引用Teacher_ID列。还要遵守数据类型约束。即。我不应该将整数插入 text 列,反之亦然。

请帮助它已经两天了,我已经厌倦了:

public class WinnersTeachersDbHelper extends SQLiteOpenHelper {

// If you change the database schema, you must increment the database version.
private static final int DATABASE_VERSION = 1;

public static final String DATABASE_NAME = "winnersteachersbanana.db";

public WinnersTeachersDbHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Create a table to hold teachers details.
    final String SQL_CREATE_TEACHERS_TABLE = "CREATE TABLE " + Teachers.TABLE_NAME + " (" +
            Teachers._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +

            Teachers.COLUMN_FULL_NAME + " TEXT NOT NULL, " +
            Teachers.COLUMN_MOBILE_NUMBER + " TEXT NOT NULL, " +

            " UNIQUE (" + Teachers.COLUMN_MOBILE_NUMBER + ") ON CONFLICT REPLACE);";

    // Create a table to hold credentials details.
    final String SQL_CREATE_CREDENTIALS_TABLE = "CREATE TABLE " + Credentials.TABLE_NAME + " (" +

            Credentials._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
            Credentials.COLUMN_TEACHER_ID + " INTEGER NOT NULL, " +
            Credentials.COLUMN_USERNAME + " TEXT NOT NULL, " +
            Credentials.COLUMN_PASSWORD + " TEXT NOT NULL, " +

            // Set up the teacherId column as a foreign key to teachers table.
            " FOREIGN KEY (" + Credentials.COLUMN_TEACHER_ID + ") REFERENCES " +
            Teachers.TABLE_NAME + " (" + Teachers._ID + "), " +

            " UNIQUE (" + Credentials.COLUMN_TEACHER_ID + ") ON CONFLICT REPLACE);";

sqLiteDatabase.execSQL(SQL_CREATE_TEACHERS_TABLE);
sqLiteDatabase.execSQL(SQL_CREATE_CREDENTIALS_TABLE);
}

1 个答案:

答案 0 :(得分:0)

SQLite使用dynamic typing;您必须使用单独的约束强制执行列类型:

CREATE TABLE ... (
    ...,
    FullName TEXT NOT NULL  CHECK(typeof(FullName) = 'text'),
    ...
);