Ruchit
Ruchit

Reputation: 17

Android SQLite insert statement error

In my database I modified my table. previously it had 2 columns excluding id. Now it has 3 columns excluding id. So whenever i add an tuple it shows error. For adding tuple i ve called addContact function

      private static final int DATABASE_VERSION = 25;


    // Database Name
    private static final String DATABASE_NAME = "contactsManager";

    // Contacts table name
    private static final String TABLE_CONTACTS1 = "contacts";

    // Contacts Table Columns names

    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone_number";
    private static final String KEY_UNIQUE = "unique";

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

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS1 + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_UNIQUE + " INTEGER," + KEY_PH_NO + " TEXT " + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS1);

        // Create tables again
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Adding new contact
    void addContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName()); // Contact Name
        values.put(KEY_UNIQUE, contact.getUnique());
        values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone

        // Inserting Row
         //giving error at following line
        db.insert(TABLE_CONTACTS1, null, values);
        db.close(); // Closing database connection
    }

//error is Error inserting name=21:58 unique=1717 phone_number=null3 android.database.sqlite.SQLiteException: near "unique": syntax error (code 1): , while compiling: INSERT INTO contacts(name,unique,phone_number) VALUES (?,?,?)

Upvotes: 0

Views: 389

Answers (1)

laalto
laalto

Reputation: 152927

UNIQUE is a keyword in SQL and cannot be used as an identifier as such.

Rename the column name to something like isunique or similar, and uninstall your app so that the modified onCreate() is actually run.

Upvotes: 1

Related Questions