关系数据库用于存储结构化数据,移动开发中常用SQLite等轻量级数据库。数据库常见的操作是增、删、改、查,其方法如下:
一、创建数据库
假设数据库名为mydatabase.sqlite,表名为employee,包含序号(id)、姓名(name)、年龄(age)、性别(sex)、部门(department)等字段。代码如下:
private RdbStore getMyDatabaseRdbStore(){ DatabaseHelper helper = new DatabaseHelper(getContext()); StoreConfig config = StoreConfig.newDefaultConfig("mydatabase.sqlite"); RdbStore store = helper.getRdbStore(config, 1, new RdbOpenCallback() { @Override public void onCreate(RdbStore rdbStore) { rdbStore.executeSql("CREATE TABLE IF NOT EXISTS employee (" "id INTEGER PRIMARY KEY AUTOINCREMENT," "name TEXT NOT NULL," "age INTEGER," "sex TINYINT," "department TEXT)"); } @Override public void onUpgrade(RdbStore rdbStore, int i, int i1) { } }); return store; }
二、增加数据
通过4个TextField(tfName、tfAge、tfSex、tfDepartment)获得输入数据并存储,将操作情况显示在Text组件(text)上。
RdbStore store = getMyDatabaseRdbStore();ValuesBucket values = new ValuesBucket();try {String name = tfName.getText();int age = Integer.parseInt(tfAge.getText());int sex = Integer.parseInt(tfSex.getText());String department = tfDepartment.getText();values.putString("name",name);values.putInteger("age",age);values.putInteger("sex",sex);values.putString("department",department);}catch (Exception e){e.printStackTrace();}long id = store.insert("employee",values);if(id == -1){text.setText("增加数据失败!");}else{text.setText("增加数据成功,序号: " id "。");}store.close();
三、删除数据
从TexeField中获取删除条件,执行删除操作,将结果显示在Text组件上。
String searchName = tfSearch.getText();RdbStore Store = getMyDatabaseRdbStore();RdbPredicates rdbPredicates = new RdbPredicates("employee").equalTo("name",searchName); int rowNum = Store.delete(rdbPredicates);if(rowNum == -1){text.setText("删除失败");}else{text.setText("删除成功");}Store.close();
四、更新数据
从TexeField中获取更新数据条件,将其“部门”修改为“研发部”,将结果显示在Text组件上。
String searchName = tfSearch.getText();RdbStore store = getMyDatabaseRdbStore();RdbPredicates rdbPredicates = new RdbPredicates("employee") .equalTo("name",searchName);ValuesBucket bucket = new ValuesBucket();bucket.putString("department","研发部");int rowNum = store.update(bucket,rdbPredicates);if(rowNum == -1){text.setText("更新失败");}else{text.setText("更新成功");}store.close();
五、查询数据
通过1个TextField获得查询的条件(如人员姓名),实现模糊查找,显示在Text组件上。
RdbStore store = getMyDatabaseRdbStore();String searchName = tfSearch.getText();String[] col = new String[]{"id","name","age","sex","department"};text.setText("");if(searchName != null){ResultSet resultSet = store.querySql("select * from employee where " "name like ?",new String[]{"%" searchName "%"});String showtext = "";while(resultSet.goToNextRow()) {int id = resultSet.getInt(0);String name = resultSet.getString(1);int age = resultSet.getInt(2);int sex = resultSet.getInt(3);String department = resultSet.getString(4);showtext = id " . " name " - " age " - " sex " - " department; text.setText(showtext ="n");}resultSet.close();}store.close();
在更新、删除等操作中常先进行查找操作,判断所更新、删除的数据是否存在,进而进行下步操作,此处省略。每种操作之后要把数据库关闭。
花粉社群VIP加油站
猜你喜欢