安卓常用数据存储方式之一SQLite学习及操作笔记
0.视频地址:http://www.imooc.com/video/3382
1.每个程序都有自己的数据库 默认情况下是各自互不干扰
1)创建一个数据库并且打开;
SQLiteDatabase db=openOrCreateDatabase("user.db",MODE_PRIVATE,null);
2)使用游标cursor相当于存储结果的集合,可理解为list;
3)结束后必须释放游标。
2.具体代码:
1 public class MainActivity extends Activity { 2 3 @Override 4 protected void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setContentView(R.layout.activity_main); 7 8 //每个程序都有自己的数据库 默认情况下是各自互不干扰 9 //1.创建一个数据库并且打开 10 SQLiteDatabase db=openOrCreateDatabase("user.db",MODE_PRIVATE,null); 11 db.execSQL("create table if not exists usertb(_id integer primary key autoincrement," + 12 "name text not null,age integer not null,sex text not null)"); 13 //创建用户表 包括 _id主键,姓名,年龄,性别 14 db.execSQL("insert into usertb(name,age,sex)values('张三','男',26)"); 15 db.execSQL("insert into usertb(name,age,sex)values('刘明','男',22)"); 16 db.execSQL("insert into usertb(name,age,sex)values('于思','女',21)"); 17 18 //2.使用游标cursor相当于存储结果的集合,可理解为list 19 Cursor c=db.rawQuery("select*from usertb",null); 20 if(c!=null){ 21 while(c.moveToNext()){ 22 Log.i("info","_id:"+c.getInt(c.getColumnIndex("_id"))); 23 Log.i("info","name:"+c.getString(c.getColumnIndex("name"))); 24 Log.i("info","sex:"+c.getString(c.getColumnIndex("sex"))); 25 Log.i("info","age:"+c.getInt(c.getColumnIndex("age"))); 26 Log.i("info","!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); 27 } 28 c.close();//3.释放游标 29 } 30 db.close(); 31 } 32 }
3.运行结果:
4.知识点小记:
1)可以使用工具navicat打开并查看db格式文件,查看自己创建的用户表;
2)游标cursor相关: