首先创建一个类继承自SQLiteOpenHelper,然后重写构造方法和onCreate和onUpGrade,在oncreate中创建表
db.execSQL("create table hero(_id integer Primary Key autoincrement,name text(20))");
方便学习实现了增删改查功能,
添加功能
//添加 addButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String name = add.getText().toString(); SQLiteDatabase db = bhelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", name); long id = db.insert("hero", "name", values); if (id != -1) { Toast.makeText(MainActivity.this, "插入成功", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(MainActivity.this, "插入失败", Toast.LENGTH_SHORT).show(); } db.close(); } });
//修改 alter.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String name = add.getText().toString(); SQLiteDatabase db = bhelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", name); int cnt = db.update("hero", values, "_id = ?", new String[]{id + ""}); if(cnt>0){ Toast.makeText(MainActivity.this, "修改成功", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(MainActivity.this, "修改失败", Toast.LENGTH_SHORT).show(); } db.close(); } });
//查看 look.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String name = add.getText().toString(); SQLiteDatabase db = bhelper.getReadableDatabase(); String selection = null; String[] selectionArgs = null; if (!"".equals(name)) { selection = " name like ?";//只查询name的模糊查询 selectionArgs = new String[]{name + "%"}; } Cursor c = db.query("hero", new String[]{"_id","name"}, selection, selectionArgs, null, null, "name asc"); SimpleCursorAdapter sca = new SimpleCursorAdapter(MainActivity.this, R.layout.person_item, c, new String[]{"name"}, new int[]{R.id.nameTv}); listView.setAdapter(sca); startManagingCursor(c); db.close(); } });
//删除 delete.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { SQLiteDatabase db = bhelper.getWritableDatabase(); int cnt = db.delete("hero","_id = ?", new String[]{id +""}); if(cnt>0){ Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(MainActivity.this, "修改失败", Toast.LENGTH_SHORT).show(); } db.close(); } });