Android中SQLite数据库小结

发表于:2013-12-24 10:08

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:byhook    来源:51Testing软件测试网采编

  向数据库中增加数据:两种方法
  第一种用系统提供的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();
22/2<12
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号