SQLiteDatabase

来源:互联网 发布:java精品课程网 编辑:程序博客网 时间:2024/06/04 20:03

DbUtils

public class DbUtils{    public static final String DATABASE_NAME="info";  //数据库名称    public static final int DATABASE_VERSION=1;  //数据库版本    public static final String TABLE_NAME="student";  //创建表名    public static final String STUDENT_ID="_id";  //表 _id 字段    public static final String STUDENT_NAME="name";  //表name字段    public static final String STUNDENT_AGE="age";  //表age 字段}

MySqliteHelper

public class MySqliteHelper extends SQLiteOpenHelper{    private static String TAG="MySqliteHelper";    public MySqliteHelper(Context context,String name,CursorFactory factory,int version){        super(context,name,factory,version);    }    public MySqliteHelper(Context context){        super(context,DbUtils.DATABASE_NAME,null,DbUtils.DATABASE_VERSION);    }    /**    表示当前数据库被创建时回调的方法    数据库创建的同时创建数据表student    */    public void onCreate(SQLiteDatabase db){        String sql = "create table "+DbUtils.TABLE_NAME+"("+DbUtils.STUDENT_ID+" integer primary key,"+DbUtils.STUDENT_NAME+" varchar(10),"+DbUtils.STUNDENT_AGE+" integer";        db.execSQL(sql);    }    /**    表示数据库版本发生改变时回调的方法    */    public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){        if(newVersion>oldVersion){            //版本更新后的具体操作            //TODO  待实现        }    }    /**    表示数据库被打开时回调的方法    */    public void onOpen(SQLiteDatabase db){        super.onOpen(db);    }}

DbManager

public class DbManager{    //获取helper对象的方法    public static MySqliteHelper getInstance(Context context){        if(helper==null){            helper = new MySqliteHelper(context);        }        return helper;    }    /**    根据传递的sql语句指定相应的操作    */    public static void execuDataSql(SQLiteDatabase db,String sql){        if(db!=null){            if(!"".equals(sql)&&sql!=null){                db.execSQL(sql);            }        }    }    /**    采用api中提供的方法插入数据    */    public static long insertData(SQLiteDatabase db,String table,String nullColumnHack,ContentValues values){        long count=0;        if(db!=null){            count = db.insert(table,nullColumnHack,values);        }           return count;    }    /**    采用api提供的方法修改数据    */    public static int updateData(SQLiteDatabase db,String table,ContentValues values,String whereClause,String[] whereArgs){        int count=0;        if(db!=null){            count = db.update(table,values,whereClause,whereArgs);        }        return count;    }    /**    采用api方法删除数据    */    public static int deleteData(SQLiteDatabase db,String table,String whereClause,String[] whereArgs){        int count = 0;        if(db!=null){            count = db.delete(table,whereClause,whereArgs);        }        return count;    }    /**    通过sql语句查询数据表    rawQuery(查询sql语句,查询sql语句中占位符赋值的字符串数组)    */    public static List<Student> queryBySql(SQLiteDatabase db,String sql,String[] selectionArgs){        Cursor cursor = null;        if(db!=null){            cursor =db.rawQuery(sql,selectionArgs);        }        return cursorToList(cursor);    }    /**    将cursor 对象转换成list集合    */    public static List<Student> cursorToList(Cursor cursor){        List<Student> list=new ArrayList<Student>();        while(cursor.moveToNext()){            //将每条记录的每个字段对应的值获取   存储到student对象中,将student对象存储到list集合中            //getColumnIndex(String indexName) 根据字段名称获取字段的下标            int indexId = cursor.getColumnIndex(Dbutils.STUDNET_ID);            int id=cursor.getInt(indexId);//getInt(int index) 根据指定下标获取指定的int类型的数据            String name =cursor.getString(cursor.getColumnIndex(Dbutils.STUDENT_NAME));            int age = cursor.getInt(cursor.getColumnIndex(Dbutils.STUNDET_AGE));            Student student = new Student(id,name,age); //以解析的字段值构建student 对象            list.add(student);  //将对象存储到集合        }        return list;    }    /**    select 字段名 from 表名 where xxx group bu 分组字段 having 筛选 order by 排序字段 desc(asc)    */    public static List<Student> queryByApi(SQLiteDatabase db,String table,String[] columns,String selection,String[] selectionArgs,String groupBy,String having,String orderBy){        Cursor cursor=null;        if(db!=null){            cursor = db.query(table,columns,selection,selectionArgs,groupBy,having,orderBy);        }        return cursorToList(cursor);    }    /**    关闭指定的数据库    */    public static void closeDb(SQLiteDatabase db){        if(db!=null){            db.close();        }    }}

MainActivity

public class MainActivity extends Activity{    private MySqliteHelper helper;    protected void onCreate(Bundle savedInstanceState){        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        helper = DbManger.getInstance(MainActivity.this);    }    // 点击按钮创建数据库    public void create_database(View view){        /*        调用helper类的getReadableDatabse() getWriteableDatabase()创建或者打开数据库  获取数据库对象        如果该数据库不存在则创建,如果该数据库存在则打开数据库        getReadableDatabase() getWriteableDatabase() 默认情况下返回的都是可读可写的数据库对象        如果出现一些问题例如磁盘已满或者是数据库本身是只读权限getReadableDatabase()方法返回的就是只读的数据库对象        */        SQLiteDatabase db= helper.getReadableDatabase();    }    //根据点击的按钮执行相应的增删改操作    public void click(View view){        switch(view.getId()){            case R.id.button_insert:                SQLiteDatabase db =helper.getWritableDatabase(); //打开数据库                //对数据库操作                String sql = "insert into "+Dbutils.TABLE_NAME+" values(1,'zhangsan',30)";                DbManger.execDataSql(db,sql);                String sql2 = insert into "+Dbutils.TABLE_NAME+" values(2,'lisi',26)";                Dbutils.execDataSql(db,sql2);                //关闭数据库                DbManger.closedDb(db);                break;            case R.id.button_update://点击按钮完成修改数据                db =helper.getWritableDatabase();                String sql3 = "update from "+Dbutils.TABLE_NAME+" where "+Dbutils.STUDENT_ID+"=1";                DbManger.execDataSql(db,sql3);                DbManger.closedDb(db);                break;            case R.id.button_delete://点击按钮删除数据                db = helper.getWritableDatabase();                String sql4="delete from "+Dbutils.TABLE_NAME+" where "+Dbutils.STUDENT_ID+" =1";                DbManger.execDataSql(db,sql4);                DbManger.closedDb(db);                break;        }    }    /**    采用api提供的方法增删改操作数据表    */    public void onClick(View view){        switch(view.getId()){            case R.id.button_apiinsert: //点击按钮采用api形式插入数据                SQLiteDatabase db=helper.getWritableDatabase();                ContentValues values=new ContentValues();                values.put(Dbutils.STUDENT_ID,3); //put(表示当前插入数据表的字段,表示当前插入key指定字段的值)                values.put(Dbutils.STUDENT_NAME,"小鹿");                values.put(Dbtils.STUDENT_AGE,23);                long count=DbManger.insertData(db,Dbutils.TABLE_NAME,null,values);                if(count>0){                    Toast.makeText(MainActivity.this,"插入数据成功",Toast.LENGTH_SHORT).show();                }else{                    Toast.makeText(MainActivity.this,"插入数据失败",Toast.LENGTH_SHORT).show();                }                DbManger.closeDb(db);                break;            case R.id.button_apiupdate:  // 点击按钮采用api形式修改数据                db = helper.getWritableDatabase();                ContentValues values2=new ContentValues();                values2.put(Dbutils.STUDENT_NAME,"心心");                values2.put(Dbutils.STUDENT_AGE,2);                int count1=DbManger.updateData(db,Dbutils.TABLE_NAME,values2,""+Dbutils.STUDENT_ID+"=?",new String[]{"3"});                if(count>0){                    Toast.makeText(MainActivity.this,"修改数据成功",Toast.LENGTH_SHORT).show();                }else{                    Toast.makeText(MainActivity.this,"修改数据失败",Toast.LENGTH_SHORT).show();                }                DbManger.closeDb(db);                break;            case R.id.button_apidelete:                db =helper.getWritableDatabase();                int count2=DbManger.deleteData(db,Dbutils.TABLE_NAME,Dbutils.STUDENT_ID+"=2",null);                if(count>2){                    Toast.makeText(MainActivity.this,"删除数据成功",Toase.LENGTH_SHORT).show();                }else{                    Toast.makeText(MainActivity.this,"删除数据失败",Toast.LENGTH_SHORT).show();                   }                DbManger.closeDb(db);                break;        }    }}
0 0
原创粉丝点击