0

I'm just learning Android. I have working piece of code that uses ContentValues:

My constants:

public static final String TABLE_NAME = "numbers";
public static final String COL_ID = "_id";
public static final String COL_NUMBER = "number";

This way I create table:

db.execSQL( "CREATE TABLE " + TABLE_NAME + "( " + COL_ID +
            " integer primary key autoincrement, " + COL_NUMBER +
            " integer not null );" );

And this way I add values to the table:

ContentValues values = new ContentValues();
values.put( SQLHelper.COL_NUMBER, 1 );
long id = db.insert( SQLHelper.TABLE_NAME, null, values );

It works, but when I replace inserting with rawQuery it doesn't insert to the table anymore:

db.rawQuery( "INSERT INTO " + SQLHelper.TABLE_NAME + " VALUES( NULL, 1 )", null );

where do I make a mistake?

Thanks.

tobi
  • 1,944
  • 6
  • 29
  • 48

1 Answers1

1

db.rawQuery --> Runs the provided SQL and returns a Cursor over the result set.

db.execSQL--> Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.

Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
  • yes, I have read that, but does it mean that it doesn't run the sql statement on the database side, but only creates Cursor object and returns it? – tobi Jul 04 '12 at 10:27
  • I have found a topic on SO http://stackoverflow.com/questions/7470739/how-to-use-rawquery-to-insert-a-record?rq=1 and there some guy says to use "execSQL". But the topic is like 1 year old so it just changed during the time or what? – tobi Jul 04 '12 at 10:40
  • I've got another solution, but I don't understand why it works. I changed it to: db.rawQuery( "INSERT INTO " + SQLHelper.TABLE_NAME + " VALUES( NULL, 1 );", null ).moveToFirst(); but the documentation doesn't say anything in the moveToFirst() that it executes anything... – tobi Jul 04 '12 at 10:50