微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【Android学习笔记】SQLite数据库存储

因为前面提到xml存储更改文件很麻烦的缘故,最终还是选择了使用数据库存储

一试才觉十分的方便,速度也快

上源码:

public class DBHelper  extends sqliteOpenHelper{

    private final static String DATABASE_NAME="fanliao_db";
    private final static int DATABASE_VERSION=1;
    private final static String TABLE_NAME="fanliao_chat";
    public final static String CHAT_ID="_id"; 
    public final static String CHAT_Name="chatname";
    public final static String CHAT_Info="chatinfo";
    public final static String CHAT_Time="chattime";
    
    
    public DBHelper(Context context)
    {
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
    }
    
    
     
    @Override
    public void onCreate(sqliteDatabase db) {
       //CREATE TABLE fanliao_chat( _id  INTEGER PRIMARY KEY  AUTOINCREMENT,// chatname TEXT,chattime TEXT,chatinfo TEXT);
    	String sql="CREATE TABLE "+TABLE_NAME+"("+CHAT_ID+"  INTEGER PRIMARY KEY  AUTOINCREMENT,"
        +CHAT_Name+" TEXT,"+CHAT_Time+" TEXT,"+CHAT_Info+" TEXT);";
        db.execsql(sql);
        System.out.println(sql);
         
    }

    @Override
    public void onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) {
        String sql=" DROP TABLE IF EXISTS "+TABLE_NAME;
        db.execsql(sql);
        onCreate(db);
        System.out.println(sql);
    }

    public Cursor select()
    {
        sqliteDatabase db=this.getReadableDatabase();
        Cursor cursor=db.query(TABLE_NAME," _id asc");
        return cursor;
    }
    
    public long insert(String chatname,String chattime,String chatinfo)
    {
        sqliteDatabase db=this.getWritableDatabase();
        ContentValues cv=new ContentValues(); 
        cv.put(CHAT_Name,chatname);
        cv.put(CHAT_Time,chattime);
        cv.put(CHAT_Info,chatinfo);
        long row=db.insert(TABLE_NAME,cv);
        return row;
    }
    
    public void delete(int id)
    {
        sqliteDatabase db=this.getWritableDatabase();
        String where=CHAT_ID+"=?";
        String[] whereValue={Integer.toString(id)};
        db.delete(TABLE_NAME,where,whereValue);
    }
    
    public void update(int id,String chatname,String chatinfo)
    {
        sqliteDatabase db=this.getWritableDatabase();
        String where=CHAT_ID+"=?";
        String[] whereValue={Integer.toString(id)};
        ContentValues cv=new ContentValues(); 
        cv.put(CHAT_Name,chatinfo);
        db.update(TABLE_NAME,cv,whereValue);
    }
    
    public void delall(){
    	sqliteDatabase db=this.getReadableDatabase();
    	String sql=" DROP TABLE IF EXISTS "+TABLE_NAME;
        db.execsql(sql);
        onCreate(db);
    }
    
    
}

用后才觉得经常修改的数据本就应用数据库的,

形如“聊天记录”这种虽没有十分复杂的存储结构,也是适宜存在表中,

而xml大概多是用以传输数据或存储少量不常用改动的数据把~

原文地址:https://www.jb51.cc/sqlite/202291.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐