Manikandan
Manikandan

Reputation: 1519

Set Auto increment to a column in Sqlite database in android

I have used the following code to create a database using Sqlite. I have set auto increment to a column. When I try to insert values to the table it gives error.

db.execSQL("CREATE TABLE IF NOT EXISTS "
                + SAMPLE_TABLE_NAME
                + " (user_id INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR,age VARCHAR, zipcode VARCHAR,gender VARCHAR,isstored VARCHAR);");
        db.execSQL("INSERT INTO " + SAMPLE_TABLE_NAME + " Values ("
                + "\"" + name + "\"," + "\"" + age
                + "\",\"" + zip + "\",\"" + gender + "\", \""
                + "ok" + "\");");

Error:

 09-28 09:44:54.545: E/AndroidRuntime(3825): java.lang.RuntimeException: Unable to   start activity ComponentInfo{com.readometer/com.readometer.ReadometerSplash}: 
android.database.sqlite.SQLiteException: table USERDETAILS has 6 columns but 5 values were supplied (code 1): , while compiling: INSERT INTO USERDETAILS Values ("kumar","23","1234","M", "ok");

Upvotes: 0

Views: 4105

Answers (4)

vineeth
vineeth

Reputation: 61

Try this code:

SQLiteDatabase s =getWritableDatabase();
s.execSQL( "INSERT INTO requestmsg (username ,age , zipcode ,gender ,isstored ) " +                 "VALUES ('" + name + "', '" + age+ "','" +  zip+ "','"+gender+"','ok')");

Upvotes: 1

GrIsHu
GrIsHu

Reputation: 23638

Try out as below:

sql = "INSERT INTO "+ SAMPLE_TABLE_NAME + "( username,age,zipcode,gender,isstored) " +
"VALUES ('" + name + "', '" + age + "','" + zip+ "' ,'" +gender + "' ,'"ok"' )";
db.execSQL(sql);

Upvotes: 0

Nitin Sethi
Nitin Sethi

Reputation: 1336

When you try to insert you should insert it this way. The SQlite framework will insert the auto-incremented values to the user_id column by itself.

INSERT INTO test.authors (username,age, zipcode,gender,isstored) VALUES ("kumar","23","1234","M", "ok");

Upvotes: 0

Yoann Hercouet
Yoann Hercouet

Reputation: 17976

You should do something cleaner, first declare all your column attributes as constants, and then use the following for example to do a proper insert in the DB:

ContentValues values = new ContentValues();
values.put(USERNAME, name);
values.put(AGE, age
values.put(ZIPCODE, zip);
values.put(GENDER, gender);
values.put(STORED, ok);
db.insert(SAMPLE_TABLE_NAME, null, values);

Upvotes: 1

Related Questions