向数据库中增加数据:两种方法
第一种用系统提供的API函数添加
ContentValues cv=new ContentValues(); //cv.put("id",1); //id是主键 自增长的 可以不赋值 cv.put("name","上帝"); cv.put("age","27"); db.insert("mytable",null,cv); db.close(); |
第二种方法用数据库语句
db.execSQL("insert into mytable(name,age) values(?,?)",new Object[]{"上帝","27"});
db.close();
两种方法都可以
删除数据两种方法
第一种方法
db.execSQL("delete from mytable where id=2"); //删除id=2的那一行
db.execSQL("delete from mytable where name=?", new Object[]{"上帝"}); //删除符合字段name=上帝的所有行
第二种方法
db.delete("mytable",null,null); //删除数据表里所有的数据
db.delete("mytable","id=?",new String[]{"2"}); //删除数据表mytable中字段 id=2的一整行
修改数据两种方法
第一种方法
db.execSQL("update mytable set name='神',age='23' where id=2"); //注意此处id位 主键 不可修改
//db.execSQL("update mytable set name='艾尼路',age='25' where name=?",new Object[]{"上帝"});
第二种方法
ContentValues cv=new ContentValues(); cv.put("name","艾斯"); cv.put("age","21"); db.update("mytable",cv,"id=?",new String[]{"5"}); |
查询数据库
Cursor cursor=db.query("mytable",new String[]{"id","name","age"},null,null,null,null,null); while(cursor.moveToNext()) //指向下一行 { int idindex=cursor.getColumnIndex("id"); int id=cursor.getInt(idindex); int nameindex=cursor.getColumnIndex("name"); String name=cursor.getString(nameindex); int ageindex=cursor.getColumnIndex("age"); String age=cursor.getString(ageindex); String result=id+" "+name+" "+age; Log.i("result",result); //打印日志 } |
打印的日志如下
所有对数据库的操作最后都要
db.close();