首页 > 代码库 > android下创建数据库学习笔记
android下创建数据库学习笔记
##在Android中创建一个数据库##
###步骤###
1、创建一个类继承SQLiteOpenHelper并在类中重写父类的构造方法、onCreate方法、onGrade方法(数据库的版本只能升级,不能降级)
###数据库增删改查方法##
public void add(View view){
SQLiteDatabase db = sql.getWritableDatabase();
//Random random = new Random();
//在数据库中增加一条数据
db.execSQL("insert into info (name,phone) values (?,?)", new Object[]{"张三","123456"});
db.execSQL("insert into info (name,phone) values (?,?)", new Object[]{"李四","654321"});
Toast.makeText(this,"add successfully!",Toast.LENGTH_SHORT).show();
db.close();
}
public void delete(View view){
SQLiteDatabase db = sql.getWritableDatabase();
//在数据库中删除指定数据
db.execSQL("delete from info where name=?", new Object[]{"张三"});
Toast.makeText(this,"delete successfully!",Toast.LENGTH_SHORT).show();
db.close();
}
public void upgrade(View view){
SQLiteDatabase db = sql.getWritableDatabase();
//在数据库中修改指定数据
db.execSQL("update info set phone=? where name=?", new Object[]{"111111","李四"});
Toast.makeText(this,"upgrade successfully!",Toast.LENGTH_SHORT).show();
db.close();
}
public void checkAll(View view){
SQLiteDatabase db = sql.getReadableDatabase();
//查询数据库并返回游标集cursor
Cursor cursor = db.rawQuery("select * from info", null);
//创建List集合
List<Person>list = new ArrayList<Person>();
//通过while循环遍历数据库数据
while(cursor.moveToNext()){
Person person = new Person();
person.setId(cursor.getInt(cursor.getColumnIndex("_id")));
person.setName(cursor.getString(cursor.getColumnIndex("name")));
person.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
list.add(person);
person=null;
}
cursor.close();
//遍历List集合
for(Person p:list){
System.out.println(p.toString());
}
Toast.makeText(this,"checkAll successfully!",Toast.LENGTH_SHORT).show();
db.close();
}
android下创建数据库学习笔记