0

What am I missing in my sql command?

public class PhoneDal extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = Constants.DB_NAME;

    public static final String BLOCKED_PHONES_TABLE = "BLOCKED_PHONES_TABLE";

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_BLOCKED_PHONES_TABLE =
                "CREATE TABLE "+ BLOCKED_PHONES_TABLE +
                        " ( "+ KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL DEFAULT 1, "
                        + KEY_PHONE+" TEXT, "
                        + KEY_IS_BLOCKED+" BIT," +
                        " UNIQUE "+ KEY_PHONE+" )";

        db.execSQL(CREATE_BLOCKED_PHONES_TABLE);
    }

and the error is

 android.database.sqlite.SQLiteException: near "KEY_PHONE": syntax error (code 1): , while compiling: CREATE TABLE BLOCKED_PHONES_TABLE ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL DEFAULT 1, KEY_PHONE TEXT, KEY_IS_BLOCKED BIT, UNIQUE KEY_PHONE )
            at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
2
  • Use the debugger to inspect the value of the String CREATE_BLOCKED_PHONES_TABLE (you really should learn the Java naming conventions) and paste it's value into your question. Commented Dec 31, 2014 at 13:42
  • For your reference: sqlite.org/lang_createtable.html Commented Dec 31, 2014 at 13:45

2 Answers 2

3

UNIQUE columns must be defined in parens. Change

" UNIQUE "+ KEY_PHONE+" )";

to

" UNIQUE ("+ KEY_PHONE+") )";
Sign up to request clarification or add additional context in comments.

2 Comments

but @Mousa solved my problem differently and it worked. how come it's different than yours?
This way defines a table constraint and the UNIQUE can apply to more than one column. Mousa's way defines a column constraint. I answered like this since your question was using a table constraint incorrectly. sqlite.org/lang_createtable.html
2

You have a syntax error for defining unique field
Use this KEY_PHONE + " TEXT UNIQUE" instead

Column definition in sqlite:
Column definition

1 Comment

Or even better, use spaces properly - KEY_PHONE + " TEXT UNIQUE"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.