Android基础学习之SQLite数据库

1.用到的资源
一个写好了的数据库文件
Android基础学习之SQLite数据库_第1张图片
一个弹出式菜单


<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/add" android:title="@string/add">item>
    <item android:id="@+id/remove" android:title="@string/remove">item>
    <item android:id="@+id/update" android:title="@string/update">item>
    <item android:id="@+id/query" android:title="@string/query">item>
menu>

2.布局文件中添加一个listView
3.代码部分

public class MainActivity extends Activity {
    private static final String DBNAME = "myDB.db";//数据库名
    private static final String TABLENAME = "student";//表名
    private static final String NAME_COL = "name";//表字段1
    private static final String AGE_COL = "age";//表字段2
    private ListView db_list;
    private SQLiteDatabase database;//数据库

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        db_list = (ListView) findViewById(R.id.db_list);

        createMyDB();//封装创建或打开数据库方法
        createMyTable();//封装创建表方法

        registerForContextMenu(db_list);//设置列表项弹出上下文菜单
    }

    private void createMyTable() {
        String sql = "create table student(id integer primary key autoincrement,name varchar(20),age integer)";
        try {
            database.execSQL(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void createMyDB() {
        // 打开或创建数据库
        // 1.在私有目录下创建
        // database = this.openOrCreateDatabase(DBNAME, MODE_PRIVATE, null);

        // 2.在sd卡下创建
        // String sdFile = Environment.getExternalStorageDirectory() +
        // "/"+DBNAME;
        // database = SQLiteDatabase.openOrCreateDatabase(sdFile, null);

        // 3.从apk中创建数据库(用到提前放入工程的数据库文件)
        String sdFile = Environment.getExternalStorageDirectory() + "/"
                + DBNAME;
        InputStream is = getResources().openRawResource(R.raw.mydb);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(sdFile);
            byte[] buff = new byte[1024];
            int num = -1;
            while ((num = is.read(buff)) != -1) {
                fos.write(buff, 0, num);
            }
            fos.flush();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        database = SQLiteDatabase.openOrCreateDatabase(sdFile, null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        database.close();
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getMenuInflater().inflate(R.menu.context_menu, menu);//上下文菜单绑定视图
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.c_update:

            break;
        case R.id.c_remove:

            break;
        default:
            break;
        }
        return super.onContextItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.add:
            doAdd();
            break;
        case R.id.remove:
            doRemove();
            break;
        case R.id.update:
            doUpdate();
            break;
        case R.id.query:
            doQuery();
            break;

        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void doAdd() {
        // 1.方法1
        String sql = "insert into student(name,age) values('rose',23)";
        database.execSQL(sql);

        // 2.方法2
        // ContentValues cv=new ContentValues();
        // cv.put(NAME_COL, "jack");
        // cv.put(AGE_COL, 24);
        // database.insert(TABLENAME, null, cv);

        // 3.方法3
        // String sql="insert into student(name,age) values(?,?)";
        // database.execSQL(sql, new Object[]{"karl",32});

        // 4.预编译
        // String sql="insert into student(name,age) values(?,?)";
        // SQLiteStatement stmt=database.compileStatement(sql);
        // stmt.bindString(1, "alice");
        // stmt.bindLong(2, 30);
        // stmt.executeInsert();
        // setTitle("add over.");
    }

    private void doRemove() {
        //方法1
//      String sql = "delete from student where id=?";
//      database.execSQL(sql, new Object[]{"1"});
        //方法2
        database.delete(TABLENAME, "id=? or name=?", new String[]{"1","karl"});
    }

    private void doUpdate() {
        ContentValues values=new ContentValues();
        values.put(NAME_COL, "sdsfd");
        values.put(AGE_COL, 11);
        database.update(TABLENAME, values, "id=1", null);
        ContentValues values2=new ContentValues();
        values.put(NAME_COL, "aaaaaa");
        values.put(AGE_COL, 38);
        database.update(TABLENAME, values, "id=2", null);
    }

    private void doQuery() {
        // 1.方法1
        String sql = "select id as _id , name, age from " + TABLENAME;
        Cursor cursor = database.rawQuery(sql, null);

        // 2.方法2
        // Cursor cursor=database.query(TABLENAME, null, null, null, null,null,
        // "age desc");
        // StringBuilder builder=new StringBuilder();

        // 3.方法3
        // SQLiteQueryBuilder sbuilder=new SQLiteQueryBuilder();
        // sbuilder.setTables(TABLENAME);
        // sbuilder.appendWhere("name like '%e%'");
        // Cursor cursor=sbuilder.query(database, null, null, null, null, null,
        // null);

        @SuppressWarnings("deprecation")
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_2, cursor,
                new String[] {NAME_COL, AGE_COL },
                new int[] { android.R.id.text1,
                android.R.id.text2 });

        db_list.setAdapter(adapter);
    }
}

你可能感兴趣的:(Android基础)