Insert in SQLite Database android

Richard Tunner picture Richard Tunner · Nov 2, 2012 · Viewed 54.2k times · Source

im new on Android. I have some trouble with the insert statement in the database, when im running the application the values have not been inserted. Please someone can help..

public class DatabaseAdapter extends SQLiteOpenHelper {
// Database attributes
public static final String DB_NAME = "MoneyManagerSystemTr";
public static final int DB_VERSION = 1;

// Table attributes

public static final String TABLE_ACCOUNT = "account_table";

//Account Table
public static final String KEY_BANKNAME ="bankname";
public static final String KEY_TYPE = "type";
public static final String KEY_ACCNUM = "accnum";
public static final String KEY_BALANCE = "balance";
public static final String KEY_EXPIRYDATE = "expirydate";

@Override
public void onCreate(SQLiteDatabase db) {


    String AccountTable = "create table if not exists " + TABLE_ACCOUNT + " ( " + BaseColumns._ID + " integer primary key autoincrement, " 
            + KEY_BANKNAME + " text not null, "
            + KEY_TYPE + " text, "
            + KEY_ACCNUM + " text, "
            + KEY_BALANCE + " text, "
            + KEY_EXPIRYDATE + " text);";

    db.execSQL(AccountTable);

String ROW1 = "INSERT INTO " + TABLE_ACCOUNT + " Values ('Cash','','',0, '');";
    db.execSQL(ROW1);

    String ROW2 = "INSERT INTO " + TABLE_ACCOUNT + " Values ('Bank Account','','',0, '');";
    db.execSQL(ROW2);

    String ROW3 = "INSERT INTO " + TABLE_ACCOUNT + " Values ('Credit Card','','',0, '');";
    db.execSQL(ROW3);

Answer

Tobias Moe Thorstensen picture Tobias Moe Thorstensen · Nov 2, 2012

You can use ContentValues to insert into your database.

SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_NAME, VALUE); 
values.put(COL_NAME, VALUE);

// Inserting Row
db.insert(YOUR_TABLE, null, values);