码迷,mamicode.com
首页 > 移动开发 > 详细

android下创建数据库学习笔记

时间:2016-09-09 20:30:47      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

##在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下创建数据库学习笔记

标签:

原文地址:http://www.cnblogs.com/jxtcnblogs/p/5857721.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!