Android sqlite 数据库在java代码中的增删改查

 private void queryPerson(PersonSQLiteOpenHelper personSQLiteOpenHelper) {

        SQLiteDatabase sqLiteDatabase = personSQLiteOpenHelper.getReadableDatabase();

        Cursor cursor = sqLiteDatabase.query("person", new String[]{"id", "name", "age"}, null, null, null, null, null, null);

        while(cursor.moveToNext()) {

            int id = cursor.getInt(cursor.getColumnIndex("id"));

            String name = cursor.getString(cursor.getColumnIndex("name"));

            int age = cursor.getInt(cursor.getColumnIndex("age"));

            System.out.println("id = " + id);

            System.out.println("name = " + name);

            System.out.println("age = " + age);

            System.out.println("————————————————————————————————");

        }

    }



    private void deletePerson(PersonSQLiteOpenHelper personSQLiteOpenHelper) {

        SQLiteDatabase sqLiteDatabase = personSQLiteOpenHelper.getWritableDatabase();

        sqLiteDatabase.delete("person", "id=?", new String[]{"2"});

        sqLiteDatabase.close();

    }



    /**

     * 模拟事务

     */

    private void transactionTest(){

        SQLiteDatabase sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase("/data/data/com.wuyou.sqlitetest/databases/person.db",null);

        //首先打开一个事务

        sqLiteDatabase.beginTransaction();

        try {

            sqLiteDatabase.execSQL("update person set age = 44 where id=1");



            //模拟事务失败

            String x = null;

            x.equals("");



            sqLiteDatabase.execSQL("update person set age = 11 where id=4");

            //标记事务成功

            sqLiteDatabase.setTransactionSuccessful();

        }catch (Exception e){

            System.out.println("处理事务的时候出现异常 ");

        } finally {

            //最终标记事务完成

            sqLiteDatabase.endTransaction();

            sqLiteDatabase.close();

        }

    }

    /**

     * 添加一个人

     *

     * @param sqLiteOpenHelper

     */

    public void addPerson(SQLiteOpenHelper sqLiteOpenHelper) {

        SQLiteDatabase database = sqLiteOpenHelper.getWritableDatabase();

        ContentValues contentValues = new ContentValues();

        contentValues.put("name", "wuyou");

        contentValues.put("age", 21);

        database.insert("person", null, contentValues);

        database.close();

    }



    public void updatePerson(SQLiteOpenHelper sqLiteOpenHelper) {

        SQLiteDatabase database = sqLiteOpenHelper.getWritableDatabase();

        ContentValues contentValues = new ContentValues();

        contentValues.put("name", "zhangsan");

        contentValues.put("age", 33);

        database.update("person", contentValues, "id=?", new String[]{"1"});

        database.close();

    }

 

你可能感兴趣的:(android SQLite)