SQLite operations

first to create a database
need to write a class as follow

public class SQLiteDB extends SQLiteOpenHelper {

    public static final String CREATE_DB =  "create table data ( "+
            "id integer primary key autoincrement, "+
            "name text)";

    private Context mContext;

    public SQLiteDB(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(CREATE_DB);
        Toast.makeText(mContext, "the table has been created", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

then we can use it

private SQLiteDB sqLiteDB ;
sqLiteDB = new SQLiteDB(mContext, "sqldata.db", null, 1);

then this step would create a new database, just once. would not create later.

sqLiteDB.getWritableDatabase();

2/ write to database

SQLiteDatabase db = sqLiteDB.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("name", "firstone");
                db.insert("data" , null, values);
                values.clear();

3/ read database

SQLiteDatabase db = sqLiteDB.getReadableDatabase();
//        Cursor cursor = db.query("data",);
        Cursor cursor1 = db.rawQuery("select * from data", new String[]{});

        List<String> names = new ArrayList<String>();
         while(cursor1.moveToNext())
        {
            names.add(  cursor1.getString(1));
        }

In summary:
database opereations–
1/ create,

    db.execSQL(CREATE_DB); on class database override oncreate;

2/ write,

        ContentValues values = new ContentValues();
        values.put("key", "value");-->db.insert("table",null, values);

3/ query

        Cursor cursor = db.rawQuery("SQL", new String[]{});
        cursor.getString(columns);/getBoolean or sth.

4/ delete

        db.delete("Book", "pages > ?", new String[] { "500" });

5/ update

        values.put("price", 10.99);
        db.update("Book", values, "name = ?", new String[] { "The Da
        Vinci Code" });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值