一直以来在做Android保存数据时都是要用文本文件来保存,一直觉得很麻烦。但是,SQLite数据库有不会使用。看了一点关于SQLite的一点视频,自己有做了一个小的Demo,总算对创建数据库和对数据库进行操作有了一点认识,现在我把它和大家进行分享!
第一点:SQLite数据库的创建
在这里需要使用SQLiteDatebase类,我定义一个SQLiteDatebase类的对象:
SQLiteDatebase db;
db = openOrCreateDatabase("date.db", Context.MODE_PRIVATE,null); //" date.db"是你要创建的数据库的名字
int version = db.getVersion();
//表单不存在,创建一个新的数据库
if(version<1){
db.execSQL("create table t_student(id integer primary key,name text,age text)");
db.setVersion(1);
Toast.makeText(MainActivity.this, "数据库创建成功", 3000).show(); //进行version的判断是为了不重复创建数据库
}
第二点:对数据库进行插入数据
String na = "pjc";
String ag = "18";
db.execSQL("insert into t_student(name,age) values(?,?)", new Object[]{na,ag});
第三点:对数据库进行查询
Cursor cursor = db.query("t_student",new String[]{"id","name","age"},null,null,null,null,null);
while(cursor.moveToNext()){
String name = cursor.getString(cur.getCloumnIndex("name"));
String name = cursor.getString(cur.getCloumnIndex("name"));
}
对数据库其他操作之后再进行更新!