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